Am a bit of an aesthetic programmer and I ventured into Kotlin lately. I named my static variable as val PREF_NAME = "onb"
and got an alert in android studio
I looked into this but it's contradicting in the official Kotlin documentation
Names of constants (properties marked with const, or top-level or object val properties with no custom get function that hold deeply immutable data) should use uppercase underscore-separated names:
const val MAX_COUNT = 8
val USER_NAME_FIELD = "UserName"
Is there something I am missing?
I think what you're doing is placing your val
inside a regular class, like this:
class X {
val PREF_NAME = "onb"
}
By doing this, you're giving a separate property to every instance of the class - even though they'll all have the same value, this isn't quite the same as having a single static constant in Java terms.
The places where constants are expected to be placed for them to only have a single instance are laid out in the documentation you've quoted, specifically this part:
properties marked with const, or top-level or object val properties with no custom get function
So these properties can be top level (not nested in anything else within the file):
val PREF_NAME = "onb"
Or inside an object
:
object X {
val PREF_NAME = "onb"
}
Or inside a companion object:
class X {
companion object {
val PREF_NAME = "onb"
}
}
These are also the places where you may mark a property with the const
modifier, if it's constant at compile time.
I am guessing that your property is in a class, in which case it neither top-level nor an object value:
class A {
val justAProperty = ""
}
val TOP_LEVEL_VAL_PROPERTY = ""
object B {
val OBJECT_VAL_PROPERTY = ""
}
Frankly, the difference between those is minimal. I always use camel case for all properties but for the const val
, for which I use upper case to mark their different nature.
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