Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解

1、初始化块:初始化块可以设置变量或值,以及执行有效性检查,如检查传给某构造函数的值是否有效,初始化块代码会在构造类实例时执行。

案例代码如下:

class Player3(
    _name: String, var age: Int = 20, var isNormal: Boolean
) {
    var name = _name
        get() = field.capitalize()
        set(value) {
            field = value.trim()
        }
    //次构造函数
    //我们可以定义多个次构造函数来配置不同的参数组合
    constructor(name: String) : this(name, age = 100, isNormal = false)
    constructor(name: String, age: Int) : this(name, age = 10, isNormal = false) {
        println("次构造函数")
        this.name = name.toUpperCase()
    }
    init {
        println("测试init")
        require(age > 0) {
            "age muse be positive"
        }
        require(name.isNotBlank()) {
            "player must have a name"
        }
    }
}
fun main() {
    val player = Player3(isNormal = false, _name = "Jack")
    println("${player.name}, ${player.age}, ${player.isNormal}")
    val p = Player3("Android", 10)
    println("${p.name},${p.age},${p.isNormal}")
}

输出结果如下:

测试init
Jack, 20, false
测试init
次构造函数
ANDROID,10,false

2.初始化执行的顺序

  1. 主构造函数里声明的属性
  2. 类级别的属性赋值
  3. init初始块里的属性赋值和函数调用
  4. 次构造函数里的属性赋值和函数调用

案例代码如下:

class Students(
    _name: String, val age: Int
) {
    var name = _name
    var score = 10
    private val hobby = "music"
    val subject: String
    //初始化块
    init {
        println("initializing Students...")
        subject = "math"
    }
    constructor(_name: String) : this(_name, 10) {
        score = 20
    }
}
fun main() {
    Students("Jack")
}

可以通过反编译看java代码,就清楚了,反编译代码如下

public final class StudentsKt {
   public static final void main() {
      new Students("Jack");
   }
   // $FF: synthetic method
   public static void main(String[] var0) {
      main();
   }
}
// Students.java
package kotlin04;
import kotlin.Metadata;
import kotlin.jvm.internal.Intrinsics;
import org.jetbrains.annotations.NotNull;
@Metadata(
   mv = {1, 6, 0},
   k = 1,
   d1 = {"u0000u001anu0002u0018u0002nu0002u0010u0000nu0000nu0002u0010u000enu0002bu0002nu0002u0010bnu0002bu000fu0018u00002u00020u0001Bu000fbu0016u0012u0006u0010u0002u001au00020u0003¢u0006u0002u0010u0004Bu0015u0012u0006u0010u0002u001au00020u0003u0012u0006u0010u0005u001au00020u0006¢u0006u0002u0010u0007Ru0011u0010u0005u001au00020u0006¢u0006bnu0000u001au0004bbu0010tRu000eu0010nu001au00020u0003Xu0082D¢u0006u0002nu0000Ru001au0010u000bu001au00020u0003Xu0086u000e¢u0006u000enu0000u001au0004bfu0010r"u0004bu000eu0010u0004Ru001au0010u000fu001au00020u0006Xu0086u000e¢u0006u000enu0000u001au0004bu0010u0010t"u0004bu0011u0010u0012Ru0011u0010u0013u001au00020u0003¢u0006bnu0000u001au0004bu0014u0010r¨u0006u0015"},
   d2 = {"Lkotlin04/Students;", "", "_name", "", "(Ljava/lang/String;)V", "age", "", "(Ljava/lang/String;I)V", "getAge", "()I", "hobby", "name", "getName", "()Ljava/lang/String;", "setName", "score", "getScore", "setScore", "(I)V", "subject", "getSubject", "kotlinStudy"}
)
public final class Students {
   @NotNull
   private String name;
   private int score;
   private final String hobby;
   @NotNull
   private final String subject;
   private final int age;
   @NotNull
   public final String getName() {
      return this.name;
   }
   public final void setName(@NotNull String var1) {
      Intrinsics.checkNotNullParameter(var1, "");
      this.name = var1;
   }
   public final int getScore() {
      return this.score;
   }
   public final void setScore(int var1) {
      this.score = var1;
   }
   @NotNull
   public final String getSubject() {
      return this.subject;
   }
   public final int getAge() {
      return this.age;
   }
   public Students(@NotNull String _name, int age) {
      Intrinsics.checkNotNullParameter(_name, "_name");
      super();
      this.age = age;
      this.name = _name;
      this.score = 10;
      this.hobby = "music";
      String var3 = "initializing Students...";
      System.out.println(var3);
      this.subject = "math";
   }
   public Students(@NotNull String _name) {
      Intrinsics.checkNotNullParameter(_name, "_name");
      this(_name, 10);
      this.score = 20;
   }
}

3、延迟初始化lateinit

class Player4 {
    lateinit var equipment: String
    fun ready() {
        equipment = "sharp knife"
    }
    fun battle() {
        if (::equipment.isInitialized) {//该属性初始化,执行该代码
            println(equipment)
        }
    }
}
fun main() {
    val p = Player4()
    p.ready()
    p.battle()
}

输出结果

sharp knife

 

文章来源于互联网:Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解

阅读全文
下载说明:
1、本站所有资源均从互联网上收集整理而来,仅供学习交流之用,因此不包含技术服务请大家谅解!
2、本站不提供任何实质性的付费和支付资源,所有需要积分下载的资源均为网站运营赞助费用或者线下劳务费用!
3、本站所有资源仅用于学习及研究使用,您必须在下载后的24小时内删除所下载资源,切勿用于商业用途,否则由此引发的法律纠纷及连带责任本站和发布者概不承担!
4、本站站内提供的所有可下载资源,本站保证未做任何负面改动(不包含修复bug和完善功能等正面优化或二次开发),但本站不保证资源的准确性、安全性和完整性,用户下载后自行斟酌,我们以交流学习为目的,并不是所有的源码都100%无错或无bug!如有链接无法下载、失效或广告,请联系客服处理!
5、本站资源除标明原创外均来自网络整理,版权归原作者或本站特约原创作者所有,如侵犯到您的合法权益,请立即告知本站,本站将及时予与删除并致以最深的歉意!
6、如果您也有好的资源或教程,您可以投稿发布,成功分享后有站币奖励和额外收入!
7、如果您喜欢该资源,请支持官方正版资源,以得到更好的正版服务!
8、请您认真阅读上述内容,注册本站用户或下载本站资源即您同意上述内容!
原文链接:https://www.dandroid.cn/archives/19800,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?