jtonic
12/17/2017, 2:21 PMclass A {
companion object {
const val name1 = "Antonel"
const val name2 = StringBuilder("Antonel")
}
}
error: const 'val' has type 'kotlin.text.StringBuilder /* = java.lang.StringBuilder */'. Only primitives and String are allowed
Antonel.raulraja
12/17/2017, 2:42 PMStringBuilder(...)
is a runtime computation and can't be resolved at compile time.Shawn
12/17/2017, 2:43 PMconst val
seems to be useful in cases where it’s beneficial to reuse or otherwise extract the use of string literals to a variable, but still use that string where a compile-time constant is requiredShawn
12/17/2017, 2:43 PMShawn
12/17/2017, 2:44 PMStringBuilder(...)
can’t be resolved at compile-time - can’t put a string builder in something like the .data
segment after alljtonic
12/17/2017, 3:37 PMconst val a = "a" and
@JvmStatic val a = "a"?
with @JvmStatic there is no restriction and both assignments seems to have the same intention.araqnid
12/17/2017, 6:45 PMconst
means a value can be folded into other constant expressions - @JvmStatic
adds static accessors to the companion’s class. So they are distinct things. Look at the decompilation of:
object Things {
val propertyName = "things.key"
const val constPropertyName = "things.const_key"
@JvmStatic val staticPropertyName = "things.const_key"
}
fun main(args: Array<String>) {
println(Things.propertyName)
println("property: ${Things.propertyName}")
println(Things.constPropertyName)
println("property: ${Things.constPropertyName}")
println(Things.staticPropertyName)
println("property: ${Things.staticPropertyName}")
}
You’ll see that const_key
is referenced directly in the main code (so if the const was in a library, and the library changed it, the app wouldn’t reflect that)jtonic
12/18/2017, 8:16 PM