- Code for the first Koan can be found here.
- Code for the second Koan can be found here.
- This is the 10th post in a multipart series.
If you want to read more, see our series index
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.
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<int, int>
which returns an instance of RationalNumber
, which we do as follows:
fun Int.r(): RationalNumber = RationalNumber(this, 1)
fun Pair.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:
fun task12(): List {
return arrayListOf(1, 5, 2).sortedDescending()
}