I have recently read about the const
keyword, and I\'m so confused! I can\'t find any difference between const
and the val
keyword, I
Kotlin val
keyword is for read-only properties in comparison with Kotlin var
keyword. The other name for read-only
property is immutable
.
Kotlin code:
val variation: Long = 100L
Java equivalent looks like this:
final Long variation = 100L;
We use const
keyword for immutable properties too. const
is used for properties that are known at compile-time. That's the difference. Take into consideration that const
property must be declared globally
.
Kotlin code (in playground):
const val WEBSITE_NAME: String = "Google"
fun main() {
println(WEBSITE_NAME)
}
Java code (in playground):
class Playground {
final static String WEBSITE_NAME = "Google";
public static void main(String[ ] args) {
System.out.println(WEBSITE_NAME);
}
}