我是靠谱客的博主 内向鸡翅,最近开发中收集的这篇文章主要介绍Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

前些天发现了一个蛮有意思的人工智能学习网站,8个字形容一下"通俗易懂,风趣幽默",感觉非常有意思,忍不住分享一下给大家。
????点击跳转教程

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¢u0006bnu0000u001au0004bbu0010tRu000eu0010nu001au00020u0003Xu0082u0006u0002nu0000Ru001au0010u000bu001au00020u0003Xu0086u000e¢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, "<set-?>");
      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延迟初始化详解的全部内容,希望文章能够帮你解决Kotlin 中初始化块、初始化的顺序、lateinit延迟初始化详解所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(167)

评论列表共有 0 条评论

立即
投稿
返回
顶部