Learning Kotlin: Extension Functions and Extensions On Collections

Note

This post is the first to cover multiple Koans in a single post. The 10th in our series is very simple if you're coming from C#: because Extension Functions in Kotlin are identical to Extension Methods in C#, though they’re 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 an r function for Int and Pair, which returns an instance of RationalNumber. Here’s how we implement it:

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

An additional takeaway was the Pair class, which is similar to the Tuple class from C#.

When we get into the second Koan, we’re exposed to some of Kotlin’s built-in extension functions, which come pre-packaged in the language—no setup required. Here, we use the sortedDescending extension method with a Java collection, making it a great example of mixing Java and Kotlin:

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