Kotlin init 调用顺序详解

2,650 阅读2分钟

在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,然后才到次级函数,这个时候我们就需要写自己定义的初始化方法了。

喜欢就点个收藏

一个非常丰富的开源库,如果你需要相册、录制、录音等操作,那么这个也许对你有一定的帮助: zhongjhATC/AlbumCameraRecorder: 🔥一个高效的多媒体支持操作库,可多方面的简单配置操作相册、拍照、录制、录音等功能。也支持配套使用的展示图片、视频、音频的九宫格功能。 (An efficient multimedia support operation library, can be a variety of simple configuration operation album, photo, recording, recording and other functions.Also support supporting the use of the display of pictures, video, audio of the nine grid function.) (github.com)

Kotlin Demo配合文章,用最简单的例子入门Kotlin: zhongjhATC/kotlinDemo: kotlin的例子 (github.com)