How can I late-initialize a variable in a funtion, since lateinit
is not allowed for local variables? Otherwise, what is the good pattern for this case:
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
is an expression, so
val fragment: Fragment = when (itemID) {
R.id.nav_schedule -> ScheduleFragment()
R.id.nav_coursework -> CourseworkFragment()
...
else -> throw IllegalArgumentException()
}
will work for this use case.
There is no lateinit
equivalent for local variables. Other language constructs like try
or if
are expressions as well, so this is never needed.
Update 2017-11-19
Kotlin 1.2 supports lateinit
for local variables, so
lateinit val fragment: Fragment
works starting with Kotlin 1.2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With