What is a data type?
From your life experience, you probably know that a number is not the same as a text. For example, you can perform arithmetic operations (such as multiplication) on numbers, but not on texts. Kotlin also knows it. Every variable has a type that determines possible operations and which values can be stored in it.
Variable types
A variable's type is set when it 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.
The form of a declaration with type inference looks like this:
val/var identifier = initializationIt is possible to specify the type of a variable when declaring it:
val/var identifier: Type = initialization Note, the name of a type always starts with an uppercase letter.
Let's declare the same variables while also specifying their types:val text: String = "Hello, I am studying Kotlin now."
val n: Int = 1The Int type means the variable stores an integer number (0, 1, 2, ..., 100_000_000, ...). The String type means the variable stores a string ("Hello", "John Smith"). You will learn about these and other data types in the following lessons.
You will see both of these forms used in practice. The form that uses type inference makes your code more concise and readable, but in some cases, it may be better to specify the type. For example, if we would like to declare a variable and initialize it later, the form with type inference will not work at all.
val greeting // error
greeting = "hello" val greeting: String // ok
greeting = "hello"Type mismatch
One of the most important
functions of
data types is to protect you from assigning an unsuitable value to a variable. For example, the following code will not work:
val n: Int = "abc" // Type mismatch: inferred type is String but Int was expectedSo, if you see a type mismatch error, it means you've assigned something unsuitable to a variable.The same problem occurs when you try to assign an unsuitable value to mutable variable declared using the type inference.
var age = 30 // the type is inferred as Int
age = "31 years old" // Type mismatchIn the following lessons, we will learn about the other data types and some possible problems with them.