1

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?

s1m0nw1
  • 76,759
  • 17
  • 167
  • 196
Gavriel
  • 18,880
  • 12
  • 68
  • 105

3 Answers3

3

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.

hluhovskyi
  • 9,556
  • 5
  • 30
  • 42
1

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)
hudsonb
  • 2,214
  • 19
  • 20
0

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)
} // ...
Eugen Pechanec
  • 37,669
  • 7
  • 103
  • 124