编译时常量的文档列出了属性需要满足的三个要求,以便将其声明为const val
.这些是:
"没有自定义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)
Run Code Online (Sandbox Code Playgroud)
但是,这些不会编译:
// 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()
Run Code Online (Sandbox Code Playgroud)
编译时常量的确切规则是什么?
是否有我可以在编译时常量声明中使用的函数列表?
归档时间: |
|
查看次数: |
4245 次 |
最近记录: |