Learning Kotlin: Extension Functions and Extensions On Collections

Submitted by Robert MacLean on Wed, 06/27/2018 - 09:00
**More Information** * [Code for the first Koan can be found here](https://github.com/Kotlin/kotlin-koans/tree/master/src/i_introduction/_9_Extension_Functions). * [Code for the second Koan can be found here](https://github.com/Kotlin/kotlin-koans/blob/master/src/i_introduction/_12_Extensions_On_Collections/n12ExtensionsOnCollections.kt). * This is the 10th post in a multipart series. If you want to read more, see our [series index](/learning-kotlin-introduction)

This post is the first to cover multiple Koans in a single post.

The 10th in our series is very simple coming from C# because Extension Functions in Kotlin are identical as Extension Methods in C#, though they are much cleaner in their implementation.

In their example for the Koan we add a lastChar and lastChar1 function to the String class.

  1. fun String.lastChar() = this.get(this.length - 1)
  4. // 'this' refers to the receiver (String) and can be omitted
  5. fun String.lastChar1() = get(length - 1)

For the Koan itself, we need to an r function to Int and Pair<int, int> which returns an instance of RationalNumber, which we do as follows:

  1. fun Int.r(): RationalNumber = RationalNumber(this, 1)
  2. fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second)

An additional learning on this, was the Pair<A, B> class which is similar to the Tuple class from C#.

When we get into the second Koan, we get exposed to some of the built-in extension's functions in Kotlin which ship out of the box; in this case, we use sortedDescending extension method with the Java collection. It is a great example of mixing Java and Kotlin too:

  1. fun task12(): List<Int> {
  2.     return arrayListOf(1, 5, 2).sortedDescending()
  3. }