[Kotlin] Multi ways to write constuctor in Kotlin

package com.rsk

class Customer (val name: String, val address: String, var age: Int) {
    // if we don't want to pass in the address
    constructor(name: String, age: Int) : this(name, "", age) // secondary constructor must call primary constructor
}

class AlternativeCustomer (val name: String, var age: Int) {
    var address: String

    // init will run whenever primary constructor run
    init {
        address = ""
    }

    constructor(name: String, address: String, age: Int): this(name, age) {
        this.address = address
    }
}

// Shorter version
class AnotherAlternativeCustomer (val name: String,var age: Int, val address: String = "")

 

posted @ 2020-10-27 16:42  Zhentiw  阅读(124)  评论(0编辑  收藏  举报