【问题标题】:what's the difference between val and const val in companion object?伴随对象中的 val 和 const val 有什么区别?
【发布时间】:2021-08-04 13:21:47
【问题描述】:

当我在伴随对象中编写静态最终变量时{},我有两个选择。 一个只是使用val,另一个是const val。 当我反编译这两个变量时,唯一的区别是 val 是私有的,但 const val 是公共的。 那我选什么都没有问题吗?

koltin 文件

class Test {
    companion object{
        val test = 5
        const val test2 =5
    }
}

反编译文件

@Metadata(
   mv = {1, 4, 2},
   bv = {1, 0, 3},
   k = 1,
   d1 = {"\u0000\f\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0003\u0018\u0000 \u00032\u00020\u0001:\u0001\u0003B\u0005¢\u0006\u0002\u0010\u0002¨\u0006\u0004"},
   d2 = {"Lcom/jakchang/emo/data/network/emo/Test;", "", "()V", "Companion", "EMOPlayer.app"}
)
public final class Test {
   private static final int test = 5;
   public static final int test2 = 5;
   @NotNull
   public static final Test.Companion Companion = new Test.Companion((DefaultConstructorMarker)null);

   @Metadata(
      mv = {1, 4, 2},
      bv = {1, 0, 3},
      k = 1,
      d1 = {"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\b\u0002\n\u0002\u0010\b\n\u0002\b\u0004\b\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\b\u0002¢\u0006\u0002\u0010\u0002R\u0014\u0010\u0003\u001a\u00020\u0004X\u0086D¢\u0006\b\n\u0000\u001a\u0004\b\u0005\u0010\u0006R\u000e\u0010\u0007\u001a\u00020\u0004X\u0086T¢\u0006\u0002\n\u0000¨\u0006\b"},
      d2 = {"Lcom/jakchang/emo/data/network/emo/Test$Companion;", "", "()V", "test", "", "getTest", "()I", "test2", "EMOPlayer.app"}
   )
   public static final class Companion {
      public final int getTest() {
         return Test.test;
      }

      private Companion() {
      }

      // $FF: synthetic method
      public Companion(DefaultConstructorMarker $constructor_marker) {
         this();
      }
   }
}

【问题讨论】:

    标签: android


    【解决方案1】:

    const val - 这是一个编译时间变量。应该在编译阶段就确定了。

    如果是val,它可以在运行时分配。 只是一个例子:

    companion object{
    
        const val fooConst = someCalculation()   //Not possible, only primitives and String are allowed.
        val fooVal = someCalculation()  // possible
        
    }
    

    Kotlin 语言参考中的常量: https://kotlinlang.org/docs/properties.html#compile-time-constants

    【讨论】:

    • 我已经编辑了答案,但这只是一个示例,用于解释差异。
    猜你喜欢
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 2016-11-05
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多