Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Local late initialization in Kotlin

Tags:

kotlin

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)
}
like image 708
arslancharyev31 Avatar asked Sep 15 '25 12:09

arslancharyev31


1 Answers

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.

like image 113
Ingo Kegel Avatar answered Sep 18 '25 04:09

Ingo Kegel