什么可以用编译时常量(const val)表示?

mar*_*ran 19 kotlin

编译时常量的文档列出了属性需要满足的三个要求,以便将其声明为const val.这些是:

  • 顶级或对象的成员
  • 使用String类型或基本类型初始化
  • 没有自定义的吸气剂

"没有自定义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)

编译时常量的确切规则是什么?

是否有我可以在编译时常量声明中使用的函数列表?

小智 6

对此没有确切的文档,但是可以在此处的编译器源代码中找到可以在常量表达式中使用的函数的列表。请注意,只有那些函数才能在kotlin程序包下定义的常量表达式中使用,在自定义重载运算符上,编译器将报告错误。