The val,var,const in kotlin

从生命周期上看

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.

delLogs.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const val VENDOR_NAME = "Self Learning Java blog"
val PICon = getPI()

fun getPI(): Double {
return 3.14
}

fun main(args: Array&ltString&gt) {
println("Vendor Name $VENDOR_NAME")
println("Value of PI : $PICon")
}

output:
Vendor Name Self Learning Java blog
Value of PI : 3.14

所以const是编译期常量

从用法上

const只能修饰val
const只能声明在顶层或者为Object/companion object的一个成员
const没有自定义 getter

将kotlin代码转成java代码
Kotlin:

delLogs.sh
1
2
3
const val constValue = "constValue"
val valValue = "valValue"
var varValue = "varValue"

java(部分代码):

delLogs.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public final class FunctionKt {
@NotNull
public static final String constValue = "constValue";
@NotNull
private static final String valValue = "valValue";
@NotNull
private static String varValue = "varValue";

@NotNull
public static final String getValValue() {
return valValue;
}

@NotNull
public static final String getVarValue() {
return varValue;
}

public static final void setVarValue(@NotNull String var0) {
Intrinsics.checkParameterIsNotNull(var0, "<set-?>");
varValue = var0;
}
}

可以明显的看出三者的区别:
const val可见性为public,可以直接访问
val为private,带有public的getter的函数,只能通过函数调用访问
当定义常量时,出于效率考虑,我们应该使用const val方式,避免频繁函数调用
有一种代替const val的方式如下

delLogs.sh
1
@JvmField val NAME = 89757

其内部作用是抑制编译器生成相应的getter方法,该注解修饰后则无法重写val的get方法

参考:
https://self-learning-java-tutorial.blogspot.com/2017/12/kotlin-const-vs-val.html

Author: Rick
Link: https://rcrick.github.io/2020/01/17/The-val-var-const-in-kotlin/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.
Donate
  • 微信
  • 支付寶