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

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