美文网首页
Kotlin中伴生对象的 companion object原理

Kotlin中伴生对象的 companion object原理

作者: ModestStorm | 来源:发表于2022-09-29 12:59 被阅读0次

1.companion object的使用

class Pay(val name: String, val count: Int, val type: Int) {
    //伴生对象的声明
    companion object {
        val TYPE_REDPACK = 0
        val TYPE_COUPON = 1

        fun isRedpack(price: Pay): Boolean {
            return price.type == TYPE_REDPACK
        }
    }
}

fun main() {
    val price = Pay("红包", 10, Pay.TYPE_REDPACK)
    println(Pay.isRedpack(price))
}

2.反编译字节码为java文件

public final class PayKt {
   public static final void main() {
      Pay price = new Pay("红包", 10, Pay.Companion.getTYPE_REDPACK());
      // 外部调用了这个实例
      boolean var1 = Pay.Companion.isRedpack(price);
      System.out.println(var1);
   }

   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}
// Pay.java
public final class Pay {
   @NotNull
   private final String name;
   private final int count;
   private final int type;
   private static final int TYPE_REDPACK = 0;
   private static final int TYPE_COUPON = 1;
  //在这里创建了static final类型的Companion实例
   @NotNull
   public static final Pay.Companion Companion = new Pay.Companion((DefaultConstructorMarker)null);

   @NotNull
   public final String getName() {
      return this.name;
   }

   public final int getCount() {
      return this.count;
   }

   public final int getType() {
      return this.type;
   }

   public Pay(@NotNull String name, int count, int type) {
      Intrinsics.checkParameterIsNotNull(name, "name");
      super();
      this.name = name;
      this.count = count;
      this.type = type;
   }

   //实际上生成了静态内部类Companion,供外部类调用
   public static final class Companion {
      public final int getTYPE_REDPACK() {
         return Pay.TYPE_REDPACK;
      }

      public final int getTYPE_COUPON() {
         return Pay.TYPE_COUPON;
      }

      public final boolean isRedpack(@NotNull Pay price) {
         Intrinsics.checkParameterIsNotNull(price, "price");
         return price.getType() == ((Pay.Companion)this).getTYPE_REDPACK();
      }

      private Companion() {
      }

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

相关文章

网友评论

      本文标题:Kotlin中伴生对象的 companion object原理

      本文链接:https://www.haomeiwen.com/subject/mbkvortx.html