当前位置:网站首页>[kotlin] constructor summary

[kotlin] constructor summary

2022-06-24 17:14:00 User 3702315

Primary constructor
// Kotlin  The constructor of can be written in the class header , After the class name .
//  The constructor declared in this way , We call it the main constructor .
class Person(private val name: String) {
    fun sayHello() {
        //  Arguments declared in the main constructor , They are public fields of the class by default .
        println("hello $name")
    }
}
//  Consistent with the above functions : Declare primary constructor 
class Person constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}
///  Consistent with the above functions , The modifier defaults to :public
class Person public constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}

//  If the annotation is on the main constructor , Keywords are required :constructor
class Person  @TargetApi(28) constructor(private val name: String) {
    fun sayHello() {
        println("hello $name")
    }
}

//  If there is extra code that needs to be executed in the constructor , Need to put  init  Code block 
class Person(private var name: String) {

    init {
        name = "Hello World"
    }

    internal fun sayHello() {
        println("hello $name")
    }
}
Secondary constructor
class Person(private var name: String) {

    private var description: String? = null

    init {
        name = "Hello World"
    }

    //  If there is a primary constructor , Inherit the main constructor 
    constructor(name: String, description: String) : this(name) {
        this.description = description
    }

    internal fun sayHello() {
        println("hello $name")
    }
}
原网站

版权声明
本文为[User 3702315]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/03/20210330150245415t.html