Kotlin init 调用顺序详解 如果类有主级函数 如果类没有主级函数 喜欢就点个收藏

在java中,构造函数是可以有多个的。而Kotlin稍微有点不一样,它会有主级函数,次级函数,当然java也能实现Kotlin的主级次级函数效果。

而我们要说的init就会跟构造函数有密切关系。让我们直接看结果

调用顺序:主级函数>init>次级函数

如果类有主级函数

代码如下:

// 主级函数
class CustomView(context: Context, attrs: AttributeSet?) :
    FrameLayout(context, attrs) {

    // 次级函数
    constructor(context: Context) : this(context, null)

    init {
        Log.d("CustomView",attrs.toString())
    }
}

我们会发现,在init里面可以直接使用主级函数的attrs,那是因为在调用init之前,主机函数已经调用了

如果类没有主级函数

代码

class CustomView2 : FrameLayout {

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr
    ) {
        Log.d("CustomView2", "顺序2:constructor")
        initCustom(attrs)
    }

    init {
        Log.d("CustomView2", "顺序1:init")
    }

    private fun initCustom(attrs: AttributeSet?) {
        Log.d("CustomView2", "顺序3:initCustom" + attrs.toString())
    }

}

结果如下:
CustomView2: 顺序1
CustomView2: 顺序2
CustomView2: 顺序3

我们可以看到,如果没有主级函数,就会先调用init,然后才到次级函数,这个时候我们就需要写自己定义的初始化方法了。

喜欢就点个收藏

一个非常丰富的开源库,如果你需要相册、录制、录音等操作,那么这个也许对你有一定的帮助:
https://www.jianshu.com/p/8a0accffd0e1

Kotlin Demo配合文章,用最简单的例子入门Kotlin:
https://www.jianshu.com/p/8a0accffd0e1

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章