Extension functions

Quite often, you come across a situation where a type that you don't have control over will benefit from an extra function. Maybe you've always wished String had a reverse() function or perhaps list had a drop function that would return a copy of list with the first k elements removed.

An object-orientated approach would be to extend the type, thereby creating a subtype that adds the required new functions:

    abstract class DroppableList<E> : ArrayList<E>() { 
      fun drop(k: Int): List<E> { 
        val resultSize = size - k 
        when { 
          resultSize <= 0 -> return emptyList<E>() 
          else -> { 
            val list = ArrayList<E>(resultSize) 
            for (index in k..size - 1) { 
              list.add(this[index]) 
            } 
            return list 
          } 
        } 
      } 
    } 

But this isn't always possible. A class may be defined ...

Get Programming Kotlin now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.