Kotiln伴生对象

Kotiln伴生对象

2024-06-30
编程开发

写法

class Test {
    companion object {
    }
}

反编译后

public final class Test {
   @NotNull
   public static final Companion Companion = new Companion((DefaultConstructorMarker)null);

   public static final class Companion {
        ......
   }
}

编译器自动创建了一个public static类型的Companion实例,我们再添加一些变量看看

class Test {
    companion object {
        val aaa = 123
        fun bbb() {
            println("Hello")
        }
    }
}

反编译结果

public final class Test {
   private static final int aaa = 123;
   @NotNull
   public static final Companion Companion = new Companion((DefaultConstructorMarker)null);

   public static final class Companion {
      public final int getAaa() {
         return Test.aaa;
      }

      public final void bbb() {
         String var1 = "Hello";
         System.out.println(var1);
      }
   }
}

由于Companion对象是public static类型的,所以Companion类中定义的变量和函数,我们都可以调用到

结论

kotlin伴生对象可用来代替java中的静态常量写法

THE END
0/500
暂无评论