Data types
Introducció
4388
All of us know that a number and a piece of text are pretty different. How do we know this? Well, you can perform arithmetic operations (such as multiplication) on numbers but not on texts.
Kotlin also knows it. That’s why every variable has a type that determines what possible operations you can perform on this variable and which values you can store in it.
Variable types
A variable’s type is set when the variable is declared:
val text = "Hello, I am studying Kotlin now."
val n = 1In this case, Kotlin knows that text is a string and n is a number.
Kotlin determines the types of both variables automatically. This mechanism is called type inference.
You can also specify the type of a variable when declaring it.
Let’s declare the same variables as in the previous example and specify their types:
val text: String = "Hello, I am studying Kotlin now."
val n: Int = 1The Int type means that the variable stores an integer number (0, 1, 2, …, 100_000_000, …).
The String type means that the variable stores a string (“Hello”, “John Smith”). Later, you will learn more about these and other data types.
You will see that people use both these forms of variable declaration in practice.
When you use type inference, you make your code more concise and readable, but in some cases, it may be better to specify the type.
For example, if we need to declare a variable and initialize it later, type inference won’t work at all.
val greeting // error
greeting = "hello"The example above is incorrect because Kotlin cannot infer the type of the variable when it is merely declared, while every variable must have a type.
On the contrary, the example below does work because the type is specified by the programmer:
val greeting: String // ok
greeting = "hello"Estàs llegint una vista prèvia.
Inicia sessió per llegir l'article complet. Qualsevol compte obre 4 articles gratuïts al mes; l'alumnat i el professorat llegeixen les pàgines del seu curs sense límit.
Inicia sessió