【发布时间】:2017-07-05 09:08:52
【问题描述】:
编译时常量的文档列出了属性需要满足的三个要求,才能将其声明为const val。它们是:
- 对象的顶级或成员
- 使用 String 类型或原始类型的值初始化
- 没有自定义 getter
“无自定义 getter”要求让我相信我不能在常量声明中使用任何函数,但事实似乎并非如此。这些编译:
const val bitmask = (5 shl 3) + 2
const val aComputedString = "Hello ${0x57.toChar()}orld${((1 shl 5) or 1).toChar()}"
const val comparedInt = 5.compareTo(6)
const val comparedString = "Hello".compareTo("World!")
const val toStringedInt = 5.compareTo(6).toString()
const val charFromString = "Hello World!".get(3)
但是,这些不会编译:
// An extension function on Int.
const val coercedInt = 3.coerceIn(1..5)
// Using operator syntax to call the get-function.
const val charFromString = "Hello World!"[3]
// An immediate type is not a primitive.
const val stringFromImmediateList = "Hello World!".toList().toString()
// Using a function defined by yourself.
fun foo() = "Hello world!"
const val stringFromFunction = foo()
编译时常量的确切规则是什么?
是否有我可以在编译时常量声明中使用的函数列表?
【问题讨论】:
标签: kotlin