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) } 

when是一个表达,如此

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

将为这个用例工作。

本地变量没有lateinit等价物。 其他的语言结构像tryif也是表达式,所以这是不需要的。