您的位置:首页 > 科技 > IT业 > Kotlin单例、数据类、静态

Kotlin单例、数据类、静态

2024/10/6 10:27:58 来源:https://blog.csdn.net/studyForMokey/article/details/140580057  浏览:    关键词:Kotlin单例、数据类、静态

文章目录

  • 1. 数据类
  • 2. 单例
  • 3. 静态

1. 数据类

data class Cellphone(val brand: String, val price: Double)

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

public final class Cellphone {@NotNullprivate final String brand;private final double price;@NotNullpublic 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;}@NotNullpublic final String component1() {return this.brand;}public final double component2() {return this.price;}@NotNullpublic final Cellphone copy(@NotNull String brand, double price) {Intrinsics.checkNotNullParameter(brand, "brand");return new Cellphone(brand, price);}// $FF: synthetic methodpublic 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);}@NotNullpublic 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里面差不多

object Singleton {
}

3. 静态

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

class BookKotlin {companion object {@JvmFieldvar nameStatic: String = "BB"@JvmStaticfun speakStatic() {}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com