Kotlin单例、数据类、静态

文章目录

  • [1. 数据类](#1. 数据类)
  • [2. 单例](#2. 单例)
  • [3. 静态](#3. 静态)

1. 数据类

kotlin 复制代码
data class Cellphone(val brand: String, val price: Double)

自动生成了get set hashcode equals toString等方法。通过反编译(打开AS,在Tools-Kotlin-ShowBytecode-Decompile)可以得到如下结果

kotlin 复制代码
public final class Cellphone {
   @NotNull
   private final String brand;
   private final double price;

   @NotNull
   public final String getBrand() {
      return this.brand;
   }

   public final double getPrice() {
      return this.price;
   }

   public Cellphone(@NotNull String brand, double price) {
      Intrinsics.checkNotNullParameter(brand, "brand");
      super();
      this.brand = brand;
      this.price = price;
   }

   @NotNull
   public final String component1() {
      return this.brand;
   }

   public final double component2() {
      return this.price;
   }

   @NotNull
   public final Cellphone copy(@NotNull String brand, double price) {
      Intrinsics.checkNotNullParameter(brand, "brand");
      return new Cellphone(brand, price);
   }

   // $FF: synthetic method
   public static Cellphone copy$default(Cellphone var0, String var1, double var2, int var4, Object var5) {
      if ((var4 & 1) != 0) {
         var1 = var0.brand;
      }

      if ((var4 & 2) != 0) {
         var2 = var0.price;
      }

      return var0.copy(var1, var2);
   }

   @NotNull
   public String toString() {
      return "Cellphone(brand=" + this.brand + ", price=" + this.price + ")";
   }

   public int hashCode() {
      String var10000 = this.brand;
      return (var10000 != null ? var10000.hashCode() : 0) * 31 + Double.hashCode(this.price);
   }

   public boolean equals(@Nullable Object var1) {
      if (this != var1) {
         if (var1 instanceof Cellphone) {
            Cellphone var2 = (Cellphone)var1;
            if (Intrinsics.areEqual(this.brand, var2.brand) && Double.compare(this.price, var2.price) == 0) {
               return true;
            }
         }

         return false;
      } else {
         return true;
      }
   }
}

2. 单例

class改成object,其他的跟java里面差不多

kotlin 复制代码
object Singleton {
}

3. 静态

companion object

@JvmField - 修饰静态变量

@JvmStatic - 修饰静态方法

@JvmField 和 @JvmStatic 只能写在 object 修饰的类或者 companion object 里,写法虽然有些别扭,但是效果是真的是按 static 来实现的

kotlin 复制代码
class BookKotlin {
    companion object {
        @JvmField
        var nameStatic: String = "BB"
        @JvmStatic
        fun speakStatic() {
        }
    }
}
相关推荐
朝新_3 小时前
【多线程初阶】阻塞队列 & 生产者消费者模型
java·开发语言·javaee
立莹Sir3 小时前
Calendar类日期设置进位问题
java·开发语言
风逸hhh4 小时前
python打卡day46@浙大疏锦行
开发语言·python
火兮明兮4 小时前
Python训练第四十三天
开发语言·python
季鸢4 小时前
Java设计模式之状态模式详解
java·设计模式·状态模式
@yanyu6665 小时前
springboot实现查询学生
java·spring boot·后端
ascarl20105 小时前
准确--k8s cgroup问题排查
java·开发语言
magic 2455 小时前
Lombok 的 @Data 注解失效,未生成 getter/setter 方法引发的HTTP 406 错误
java
爱敲代码的憨仔5 小时前
分布式协同自动化办公系统-工作流引擎-流程设计
java·flowable·oa
纪元A梦5 小时前
分布式拜占庭容错算法——PBFT算法深度解析
java·分布式·算法