Kotlin: Return can be lifted out of 'when'

后端 未结 3 1226
清歌不尽
清歌不尽 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:08

    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
      }
      

提交回复
热议问题