Kotlin 中的本地后期初始化

ars*_*v31 3 kotlin

由于lateinit局部变量不允许,如何后期初始化函数中的变量?否则,这种情况的好模式是什么:

private fun displaySelectedScreen(itemID: Int) {
    //creating fragment object
    val fragment: Fragment
    //initializing the fragment object which is selected
    when (itemID) {
        R.id.nav_schedule -> fragment = ScheduleFragment()
        R.id.nav_coursework -> fragment = CourseworkFragment()
        R.id.nav_settings -> {
            val i = Intent(this, SettingsActivity::class.java)
            startActivity(i)
        }
        else -> throw IllegalArgumentException()
    }
    //replacing the fragment, if not Settings Activity
    if (itemID != R.id.nav_settings) {
        val ft = supportFragmentManager.beginTransaction()
        ft.replace(R.id.content_frame, fragment)// Error: Variable 'fragment' must be initialized
        ft.commit()
    }
    drawerLayout.closeDrawer(GravityCompat.START)
}
Run Code Online (Sandbox Code Playgroud)

Ing*_*gel 6

when 是一个表达式,所以

val fragment: Fragment = when (itemID) {
    R.id.nav_schedule -> ScheduleFragment()
    R.id.nav_coursework -> CourseworkFragment()
    ...
    else -> throw IllegalArgumentException()
}
Run Code Online (Sandbox Code Playgroud)

将适用于此用例。

lateinit局部变量没有等价物。其他语言结构也像try或是if表达式,因此永远不需要。


更新 2017-11-19

Kotlin 1.2 支持lateinit局部变量,所以

lateinit val fragment: Fragment
Run Code Online (Sandbox Code Playgroud)

从 Kotlin 1.2 开始工作。