Kotlin: Return can be lifted out of 'when'

后端 未结 3 1220
清歌不尽
清歌不尽 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条回答
  •  日久生厌
    2021-02-05 02:09

    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
        }
    }
    

提交回复
热议问题