Kotlin: Return can be lifted out of ‘when’

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 -> TITLE.type
             1 -> SUBTITLE.type
             2 -> 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 -> TITLE.type
          1 -> SUBTITLE.type
          2 -> ITEM.type
          else -> -1
     }
    

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)