In Kotlin, we use two keywords var and val to declare variables. The difference between these two keywords is that var is used to declare mutable variables, and val is used to declare immutable variables. In short, for you to understand mutable and immutable, these are concepts in Java, immutable are objects whose properties will not change after initialization, and mutable is the opposite, we can change them.
We can declare a variable in Kotlin as follows:
1 2 |
var name = "Khanh" val age = 35 |
As you can see, we do not need to declare the data type for the variable, this feature is similar to type inference with the var keyword in Java. Kotlin will automatically rely on the way the variable’s value is declared to determine what the variable’s data type is. Of course, if you want to declare the variable explicitly, you can also declare it like this:
1 2 |
var name: String = "Khanh" val age: Int = 35 |
Similar to Java, if you do not declare the data type of the variable, you must assign the variable a value, otherwise the compiler will not know what the variable’s value type is. If you do this on purpose, you will get an error immediately: