Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

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