kickopk.blogg.se

Kotlin any type
Kotlin any type













kotlin any type

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.

kotlin any type

  • var (Mutable reference) - The variable declared using var keyword can be changed later in the program.
  • val (Immutable reference) - The variable declared using val keyword cannot be changed once the value is assigned.
  • ​​​​Here, we are trying to assign 14 (integer value) to variable of different type ( String). Here, the type of language variable is not explicitly specified, nor the variable is initialized during declaration. Here are few examples that results into error.

    kotlin any type

    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).

    kotlin any type

    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.















    Kotlin any type