First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).
You just have to put your const outside your class declaration.
Two possibilities : Declare your const in your class file (your const have a clear relation with your class)
private const val CONST_USED_BY_MY_CLASS = 1
class MyClass {
// I can use my const in my class body
}
Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :
package com.project.constants
const val URL_PATH = "https:/"
Then you just have to import it where you need it :
import com.project.constants
MyClass {
private fun foo() {
val url = URL_PATH
System.out.print(url) // https://
}
}
This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :
MyClass {
companion object {
private const val URL_PATH = "https://"
const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
}
}
Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :
MyClass {
companion object {
val URL_PATH = "https://"
}
}
In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.
@JvmField val foo = Foo()