Kotlin中的本地后期初始化

时间:2017-04-03 08:06:22

标签: 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)
}

1 个答案:

答案 0 :(得分:4)

when是一个表达式,所以

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

将适用于此用例。

局部变量没有lateinit等价物。其他语言结构如tryif也是表达式,因此永远不需要这样做。

更新2017-11-19

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

lateinit val fragment: Fragment

从Kotlin 1.2开始。