从生命周期上看
The const keyword is used to define compile time constants,I.e, the value of the const variable is known at compile time. Whereas ‘val’ is used to define constants at run time.
For example, you can’t define a const like below.
const val PICon = getPI()
When you try to compile the kotlin program with above statement, you will endup in below error.
‘Const ‘val’ has type ‘Unit’. Only primitives and String are allowed’.
This is because, getPI() is evaluated at run time and assign the value to PICon, but const is used to define the constant at compile time.
Find the below working application.
1 | const val VENDOR_NAME = "Self Learning Java blog" |
所以const是编译期常量
从用法上
const只能修饰val
const只能声明在顶层或者为Object/companion object的一个成员
const没有自定义 getter
将kotlin代码转成java代码
Kotlin:
1 | const val constValue = "constValue" |
java(部分代码):
1 | public final class FunctionKt { |
可以明显的看出三者的区别:const val
可见性为public,可以直接访问
val为private,带有public的getter的函数,只能通过函数调用访问
当定义常量时,出于效率考虑,我们应该使用const val方式,避免频繁函数调用
有一种代替const val
的方式如下
1 | val NAME = 89757 |
其内部作用是抑制编译器生成相应的getter方法,该注解修饰后则无法重写val的get方法
参考:
https://self-learning-java-tutorial.blogspot.com/2017/12/kotlin-const-vs-val.html