Kotlin关键字二——constructor和init

关键字一------var和val中最后提到了构造函数,这里就学习下构造函数相关的关键字: constructor和init。

主要构造(primary constructor)

kotlin和java一样,在定义类时就自动生成了无参构造

kotlin 复制代码
// 会生成默认的无参构造函数
class Person{
}

与java不同的是,当kotlin的构造函数中必须带参数时,则需要在类名后面直接添加参数:

kotlin 复制代码
class Person(var name:String, var age:Int){
}

这种在类名后面添加参数(包含无参)的构造方法就称为主要构造(primary constructor)

次要构造(secondary constructor)

当类包含多个构造函数时,需要通过次要构造实现, 次要构造需要用constructor关键字修饰:

kotlin 复制代码
// primary constructor
class Person(var age: Int, var name: String) {
	// secondary constructor
    constructor(name: String) : this(18, name = name)
}

次要构造使用上需要注意:

  • 次要构造需要直接或间接调用主要构造

    kotlin 复制代码
    // primary constructor
    class Person(var age: Int, var name: String) {
    	// 会提示: Primary constructor call expected
        constructor(name: String)
    }
  • 次要构造中不能声明类的属性,即不能使用var或val

    kotlin 复制代码
    class Person(var age: Int, var name: String) {
        constructor(name: String) : this(age = 18, name)
        
    	// 提示'var' on secondary constructor parameter is not allowed
        constructor(var address:String, name: String):this(name)
    }

init

kotlin提供了一个方法init,当有多个构造方法,无论使用哪个构造方法都会调用到init方法:

kotlin 复制代码
// 调用 Person("xiao ming")或者 Person(16, "小明")后 都会输出
// I am a person
class Person(var age: Int, var name: String) {
    constructor(name: String) : this(age = 18, name)
    
    init {
        System.out.println("I am a person")
    }
}

可以看下实现原理:

java 复制代码
public final class Person {
   public Person(int age, @NotNull String name) {
      super();
      this.age = age;
      this.name = name;
      // init方法
      System.out.println("I am a person");
   }

   public Person(@NotNull String name) {
      this(18, name);
   }
}

可以看到kotlin构造的执行顺序是
主构造------>init()------>次要构造

相关推荐
消失的旧时光-194319 小时前
Android ble理解
java·kotlin
Jerry19 小时前
Compose 的阶段
android
Zhangzy@19 小时前
Rust 编译优化选项
android·开发语言·rust
某空m21 小时前
【Android】View滑动的实现
android
芝麻开门-新起点1 天前
Android 和 iOS 系统版本及开发适配
android·ios·cocoa
2501_915918411 天前
iOS描述文件功能解析
android·macos·ios·小程序·uni-app·cocoa·iphone
用户69371750013841 天前
一文彻底搞懂 Android 依赖配置:implementation vs testImplementation,再也不混淆!
android
TimeFine1 天前
Android WebView暗夜模式适配
android
studyForMokey1 天前
【Android Activity】生命周期深入理解
android·kotlin
浅影歌年1 天前
Android 嵌入h5顶部状态栏空白
android