Kotlin: Return can be lifted out of 'when'

后端 未结 3 1218
清歌不尽
清歌不尽 2021-02-05 01:58

The alternative to switch in Kotlin is when. So, inside a recycler view adapter, when I am returning view type, I use when:



        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-05 02:18

    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
    }
    

提交回复
热议问题