The alternative to switch in Kotlin is when. So, inside a recycler view adapter, when I am returning view type, I use when:
override fun getItemViewType(position: Int): Int { when (position) { 0 -> return ItemViewType.TITLE.type 1 -> return ItemViewType.SUBTITLE.type 2 -> return ItemViewType.ITEM.type else -> return -1 } } But, the above statement sends our warning message Return can be lifted out of 'when'.
Does anyone know what may be the correct way of using when? And what should be done to fix the above case?
In Kotlin, if-else can be used as an expression because it returns a value. Unlike java, there is no ternary operator in Kotlin because if-else returns the value according to the condition and works exactly similar to ternary.
The return keyword already is optional for functions* in Kotlin.
Labeled return in kotlin Labeled return: Using this return, control of the program is returned to the specified line in the program. This can be used as return@labelname or return@labelname value. It means return to the position labeled as labelname with the value provided.
You’re using when like a simple Java switch statement, which is okay but not very idiomatic and can be improved. You can refactor your code in two steps:
Kotlin's when can be used as an expression, it returns a value if you wish:
override fun getItemViewType(position: Int): Int { return when (position) { 0 -> ItemViewType.TITLE.type 1 -> ItemViewType.SUBTITLE.type 2 -> ItemViewType.ITEM.type else -> -1 } } The function body, now consisting of a single statement, can be changed into an expression body:
override fun getItemViewType(position: Int) = when (position) { 0 -> ItemViewType.TITLE.type 1 -> ItemViewType.SUBTITLE.type 2 -> ItemViewType.ITEM.type else -> -1 } 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