How can I write do noting in Kotlin?

Viewed 72

ESelect is a enum structure. I hope it will do noting when it is ESelect.NoAction in the following code.

It will cause compile error if I write ; after ESelect.NoAction ->, how can I fix it?

Code

aHomeViewModel.selectAction.observe(mLifecycleOwner, {
  when(it) {
    ESelect.SelectAll - > binding.chSelect.isChecked = true
    ESelect.UnselectAll - > binding.chSelect.isChecked = false
    ESelect.NoAction - > ; //It will do nothing
  }
})

enum class ESelect {
  SelectAll,
  UnselectAll,
  NoAction
}
2 Answers

You could return Unit (which is like void in Java). The code will look like:

aHomeViewModel.selectAction.observe(mLifecycleOwner, {
    when(it) {
        ESelect.SelectAll    -> binding.chSelect.isChecked = true
        ESelect.UnselectAll  -> binding.chSelect.isChecked = false
        ESelect.NoAction     -> Unit
    }
})

See the Docu: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-unit/

You could use when as an expression instead of a statement, and for the NoAction case assign the existing value:

binding.chSelect.isChecked = when (it) {
    ESelect.SelectAll -> true
    ESelect.UnselectAll -> false
    ESelect.NoAction -> binding.chSelect.isChecked
}

Or use if:

if (it == ESelect.SelectAll) {
    binding.chSelect.isChecked = true
} else if (it == ESelect.UnselectAll) {
    binding.chSelect.isChecked = false
}
Related