Kotlin - “const”背后的原因是什么

时间:2018-03-22 10:36:21

标签: kotlin constants

已经澄清了valconst val here之间的区别。

但我的问题是,为什么我们应该使用const关键字?与生成的Java代码透视图没有区别。

这个Kotlin代码:

class Application

private val testVal = "example"

private const val testConst = "another example"

生成:

public final class ApplicationKt
{
    private static final String testVal = "example";
    private static final String testConst = "another example";
}

6 个答案:

答案 0 :(得分:1)

并不总是生成相同的代码。

如果testValtestConstpublic,则生成的代码将不同。 testVal private public gettestConst,而publicconst,没有任何吸气剂。所以delete避免产生吸气剂。

答案 1 :(得分:1)

正如文档中直接提到的,testConst可用于注释参数,但testVal不能。

更一般地说,const 保证你在Java意义上有一个常量变量,并且

  

Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1), reachability (§14.21), and definite assignment (§16.1.1).

答案 2 :(得分:0)

在我看来,主要区别是val意味着不会为属性生成setter(但会生成getter),而不是值是常量,而const val是常量(如Java private/public static final xxx)。

示例:

class Foo {
    private val testVal: String
        get() = Random().nextInt().toString()
}   

答案 3 :(得分:0)

使用它们也存在差异。

常数的例子(Kotlin):

class Constants {
    companion object {
        val EXAMPLE1 = "example1" // need companion and a getter
        const val EXAMPLE2 = "example2" // no getter, but companion is generated and useless
        @JvmField val EXAMPLE3 = "example3"; // public static final with no getters and companion
    }
}

如何使用(Java):

public class UseConstants {
    public void method(){
        String ex1 = Constants.Companion.getEXAMPLE1();
        String ex2 = Constants.EXAMPLE2;
        String ex3 = Constants.EXAMPLE3;
    }
}

答案 4 :(得分:0)

您没有看到生成的代码之间的区别,因为您的变量是private。否则,结果将为getter提供testVal

  public final class ApplicationKt {
       @NotNull
       private static final String testVal = "example";
       @NotNull
       public static final String testConst = "another example";

       @NotNull
       public static final String getTestVal() {
          return testVal;
       }
    }

所以在您的特定情况下它是相同的,除了您可以在const中使用annotations属性:

const val testVal: String = "This subsystem is deprecated"
@Deprecated(testVal) fun foo() { ... }

答案 5 :(得分:0)

“常量”是编译时常量,而“ val”用于在运行时定义常量。 这意味着,“ const”永远不能分配给函数或任何类构造函数,而只能分配给String或基元。

示例:

const val NAME = "M Sakamoto"
val PICon = getPI()

fun getPI(): Double {
 return 3.14
}

fun main(args: Array<String>) {
  println("Name : $NAME")
  println("Value of PI : $PICon")
 }

输出:

Name : M Sakamoto
Value of PI : 3.14