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](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/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. fun String.lastChar() = this.get(this.length - 1)     // 'this' refers to the receiver (String) and can be omitted fun String.lastChar1() = get(length - 1) For the Koan itself, we need to an `r` function to `Int` and `Pair` which returns an instance of `RationalNumber`, which we do as follows: fun Int.r(): RationalNumber = RationalNumber(this, 1) fun Pair<Int, Int>.r(): RationalNumber = RationalNumber(first, second) An additional learning on this, was the [`Pair`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-pair/index.html) class which is similar to the [`Tuple` class from C#](https://msdn.microsoft.com/en-us/library/system.tuple.aspx). 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: fun task12(): List<Int> {     return arrayListOf(1, 5, 2).sortedDescending() }