![]() ![]() 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. 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. 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. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |