A normal val is OK, and is initialized.
class MyClass {
companion object {
private val TAG = MyClass::class.java.simpleName
}
}
But const val causes compilation error.
class MyClass {
companion object {
private const val TAG = MyClass::class.java.simpleName
}
}
error log
MyClass.kt:27:33: error: const 'val' initializer should be a constant value
private const val TAG = MyClass::class.java.simpleName
It seems unintuitive that simpleName cannot be defined as a const val.
In Kotlin, the const keyword should only be used when the value is a compile-time constant. Here MyClass::class.java.simpleName is not a compile-time constant. so we need to use val instead of const. val is same as the final keyword in Java.
For more info on this, please check here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With