Gavriel
Gavriel

Reputation: 19237

Is there a nicer way to write this in kotlin?

This is my current code:

private val EXTRA_IS_REFRESHING = "IS_REFRESHING"
private var isRefreshing: Boolean = false

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    isRefreshing = if (savedInstanceState != null)        
        savedInstanceState!!.getBoolean(EXTRA_IS_REFRESHING, false) 
        else false
}

Is there a nicer way in Kotlin to write the last line?

Upvotes: 1

Views: 93

Answers (3)

Eugen Pechanec
Eugen Pechanec

Reputation: 38243

Usually you put more than one thing into saved state. In that case I use this:

if (savedInstanceState != null) {
    // savedInstanceState is inferred non-null at this point, so no !!.
    isRefreshing = savedInstanceState.getBoolean(EXTRA_IS_REFRESHING, isRefreshing)
} else {
    // First start.
}

But that's boring. Since we're in Kotlin, I can also imagine this:

savedInstanceState?.apply {
    isRefreshing = getBoolean(EXTRA_IS_REFRESHING, isRefreshing)
} ?: run {
    // First start.
}

or

savedInstanceState?.also {
    isRefreshing = it.getBoolean(EXTRA_IS_REFRESHING, isRefreshing)
} // ...

Upvotes: 0

hudsonb
hudsonb

Reputation: 2294

You can remove the if completely in this case and assign isRefreshing to the conditional expression. Additionally, as mentioned by @s1m0nw1, smart-casting removes the need for !! or ?..

isRefreshing = savedInstanceState != null && 
               savedInstanceState.getBoolean(EXTRA_IS_REFRESHING, false)

Upvotes: 1

hluhovskyi
hluhovskyi

Reputation: 10116

One of the way is just checking if result of nullable expression equals true:

isRefreshing = savedInstanceState?.getBoolean(EXTRA_IS_REFRESHING, false) == true

Or it may be elvis operator:

isRefreshing = savedInstanceState?.getBoolean(EXTRA_IS_REFRESHING, false) ?: false

As for me first snippet of code shows intention better, so I prefer it.

Upvotes: 3

Related Questions