val means the variable is immunable, it can only be assigned once and then you cant change its value, this is like using final in java.
Kotlin uses type inference so it will detect the variable type depending on the value assigned to it at compile time, NOT at runtime, we can also tell the compiler the type.
[code]val id= 50[/code]
here it detected the type as integer
[code]val id: Int[/code]
here we said that it is int without a value
to do both at the same time
[code]val id: Int = 25[/code]
but it is not recommended because the compiler automatically detects the int when we gave the value as 50, but if you insisted, then you just told it twice.
But what if we want the type to be float?
The compiler will detect from the value 50 that it is an int, so we can use the above method just to make sure we are choosing the correct one
[code]val id: float[/code]
Because int is the default for 25 and double is default for 25.1, but if we wanted short for 25 or float for 25.1 then we need to use it like this
[code]val id: Short = 25[/code]
Now to change the value of the variable later we cant use val because it is immunable, so we have to use the word var
var id : Int
id = 20
id = 50
Now kotlion recommends using val whenever possible ( even IntelliJ underlines the variable if it isn’t immunable). so it is best practice to declare the variables as val unless we want to change it. this is the exact opposite of java which in java we declare finale when we need it not when we can.
Now if we declared a Student object as val. we cant assign a different Student instance to it, BUT we still can change the values of the instance properties.
That’s It for Declarations, for now, See you later 😀