Greetings!
Unlike Java, Kotlin uses special keywords to declare variables.
Java
Kotlin
We can use variable type when we declare it. If we initialize it, we can remove the type. But if we do not initialize, we should declare the variable type.
It will print String and Double.
Unlike Java, Kotlin uses special keywords to declare variables.
- var - for the values that change, mutable.
- val - for the values that do not change, immutable.
Java
String name = "Java";
int age = 20;
Kotlin
val name = "Kotlin"
val age = 4
It is best practice to use val because immutability guarantees safety.
We can use variable type when we declare it. If we initialize it, we can remove the type. But if we do not initialize, we should declare the variable type.
val name = "Jon Snow"
val role: String
role = "King in the north"
Constant
If the value is a truly constant we can const keyword when declaring. Though this needs to use companion object.const val THE_END = "All men must die"
Type inference
Kotlin is a strongly typed language. Compiler can deduce the type by the context eliminating boilerplate code. Compiler is smart enough to identify the variable type.val helpUs = "Save Wilpattu"
val pi = 3.14
println(helpUs::class.simpleName)
println(pi::class.simpleName)
It will print String and Double.
Comments
Post a Comment