[英]Local late initialization in 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
。 其他語言構造(例如try
或if
也是表達式),因此永遠不需要。
更新2017-11-19
Kotlin 1.2支持局部變量lateinit
,因此
lateinit val fragment: Fragment
從Kotlin 1.2開始工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.