Kotlin: Return can be lifted out of 'when'

2020-05-24 19:49发布

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?

标签: kotlin
3条回答
淡お忘
2楼-- · 2020-05-24 20:21

Your when is correct, however Kotlin has the ability to lift the return out of the 'when' if you are returning in every case, thus it becomes :

override fun getItemViewType(position: Int): Int {
    return when (position) {
        0 -> ItemViewType.TITLE.type
        1 -> ItemViewType.SUBTITLE.type
        2 -> ItemViewType.ITEM.type
        else -> -1
    }
}
查看更多
何必那么认真
3楼-- · 2020-05-24 20:30

In Kotlin, several statements, including if, when and try, can return a value. So in your case, you can refactor the statement to have the when statement return the actual value, which you can then return from the function.

So, you can simplify your method to the following:

override fun getItemViewType(position: Int): Int = when (position) {
    0 -> ItemViewType.TITLE.type
    1 -> ItemViewType.SUBTITLE.type
    2 -> ItemViewType.ITEM.type
    else -> -1
}
查看更多
▲ chillily
4楼-- · 2020-05-24 20:31

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
    }
    
查看更多
登录 后发表回答