Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Naming Conventions

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 enter image description here

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?

like image 980
Lucem Avatar asked Aug 11 '18 05:08

Lucem


Video Answer


2 Answers

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.

like image 135
zsmb13 Avatar answered Sep 20 '22 05:09

zsmb13


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.

like image 34
voddan Avatar answered Sep 21 '22 05:09

voddan