Kotlin的建筑师

N S*_*rma 35 android constructor kotlin

我正在Kotlin从官方文档中学习,我在class下面创建了一个我创建了一个constructor有两个的文档parameters.身体constructorinit块中.

class Person(name: String, surname: String) {
    init {
        Log.d("App", "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

好吧,我想创建一个更constructor将采取一个parameterconstructor.是做什么的Kotlin

cha*_*l03 43

好吧init不是构造函数的主体.它在具有主构造函数的上下文的主构造函数之后调用.

正如官方文件中所述:

主构造函数不能包含任何代码.初始化代码可以放在初始化块中,初始化块以init关键字为前缀:

class Customer(name: String) {
    init {
        logger.info("Customer initialized with value ${name}")
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,主构造函数的参数可以在初始化程序块中使用.它们也可以在类体中声明的属性初始值设定项中使用:

class Customer(name: String) {
    val customerKey = name.toUpperCase()
}
Run Code Online (Sandbox Code Playgroud)

实际上,为了声明属性并从主构造函数初始化它们,Kotlin有一个简洁的语法:

class Person(val firstName: String, val lastName: String, var age: Int) {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

根据您的问题,您可以添加一个构造函数来接受一个参数,如下所示:

class Person(name: String, surname: String) {

    constructor(name: String) : this(name, "") {
        // constructor body
    }

    init {
        Log.d("App", "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

但它看起来不正确,因为我们不必要传递第二个参数空字符串.所以我们可以命令构造函数如下:

class Person(name: String) {

    constructor(name: String, surname: String) : this(name) {
        // constructor body
    }

    init {
        Log.d("App", "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你.


Pav*_*ngh 5

第一种方式为空值

// (name: String, surname: String)  default constructor signature
class Person(name: String, surname: String) {

    // init block , represents the body of default constructor 
    init {
        Log.d("primary", "Hello");
    }

    // secondary constructor 
    // this(name,"") call to default constructor
    constructor(name : String):this(name,""){
        Log.d("secondary", "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么this(name,"")

如果类具有主构造函数,则每个辅助构造函数都需要直接或通过另一个辅助构造函数间接委托给主构造函数。委托给同一个类的另一个构造函数是使用 this 关键字完成的:

或者

kotlin 不允许nullthis(name,null)这样使用 use?来表示null具有类型的值,surname: String?

class Person(name: String, surname: String?) {

    init {
        Log.d("primary", "Hello");
    }

    constructor(name : String):this(name,null){
        Log.d("secondary", "Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)