Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin: Return can be lifted out of 'when'

Tags:

kotlin

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?

like image 405
Seop Yoon Avatar asked Dec 29 '17 05:12

Seop Yoon


People also ask

What does if return Kotlin?

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.

Does Kotlin need return?

The return keyword already is optional for functions* in Kotlin.

How do I write a return statement 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.


1 Answers

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:

  1. 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      } } 
  2. 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 } 
like image 67
s1m0nw1 Avatar answered Sep 21 '22 10:09

s1m0nw1