

That is, the type of a variable is known during the compile time. Kotlin is a statically typed language like Java. Now, you know what Kotlin variables are, it's time to learn different values a Kotlin variable can take. You cannot reassign language variable to German in the above example because the variable is declared using val. Since, the variable is declared using var, this code work perfectly. Here, language variable is reassigned to German.


Val score: Int // variable declaration of type Int Language = "French" // variable initialization Var language: String // variable declaration of type String You can declare variable and specify its type in one statement, and initialize the variable in another statement later in the program. We have initialized variable during declaration in above examples. However, you can explicitly specify the type if you want to: This is called type inference in programming. The compiler knows this by initializer expression ( "French" is a String, and 95 is an integer value in the above program).

You don't have to specify the type of variables Kotlin implicitly does that for you. Here, language is a variable of type String, and score is a variable of type Int. For now, let's focus on variable declaration. The difference in using var and val is discussed later in the article. To declare a variable in Kotlin, either var or val keyword is used. Learn more about How to name a variable in Kotlin? To indicate the storage area, each variable should be given a unique name (identifier). As you know, a variable is a location in memory (storage area) to hold data.
