O'Reilly logo

Programming Kotlin by Stefan Bocutiu, Stephen Samuel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required