[毎日Kotlin] Day13. Extension functions on collections(コレクションの拡張関数)

2018.01.30

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

はじめに

毎日Kotlinシリーズです。

このシリーズを初めての方はこちらです。「毎日Kotlin」はじめました | Developers.IO

問題

Extensions on collections | Try Kotlin

JavaコードをKotlinで扱いやすくするために作ってくれた拡張関数をつかってみよう。

Kotlin code can be easily mixed with Java code. Thus in Kotlin we don't introduce our own collections, but use standard Java ones (slightly improved). Read about read-only and mutable views on Java collections.

In Kotlin standard library there are lots of extension functions that make the work with collections more convenient. Rewrite the previous example once more using an extension function sortedDescending.

fun getList(): List<Int> {
    return arrayListOf(1, 5, 2)//TODO("return the list sorted in descending order")
}

狙い

ここで考えて欲しい問題の意図はなんだろうか?

JavaとKotlinはプロジェクト内で混ぜて使うことができます。Javaのクラス群をKotlinで書き直しましたっというより、そのまま使えるように互換性と、Kotlinで使用するときに、便利になるように拡張関数などを用意してくれています。

Kotlinのスタンダードライブラリで便利拡張関数を作っておきましたよ、ねぇ簡単でしょ?っとJetBrains神の声が聞こえてきますよね?

解答例

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

省略した解答。

fun getList() = arrayListOf(1, 5, 2).sortedDescending()

他の解答

問題の作りがうまいですね。3日間の問題は、同じでした。解答をもう一度みてみよう。

[毎日Kotlin] Day12. SAM conversions(SAM変換)

fun getList(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, { x, y -> y - x })
    return arrayList
}

[毎日Kotlin] Day11. Object expressions(オブジェクト式)

fun getList(): List<Int> {
    val arrayList = arrayListOf(1, 5, 2)
    Collections.sort(arrayList, object : Comparator<Int> {
        override fun compare(x: Int, y: Int) = y - x
    })
    return arrayList
}

あとがき

Day1 ~ 13まで毎日やっていた方はこうなっていることでしょう!おめでとう!Introductionが終わりました!

よく使う機能がまとまっていたので、かなりKotlinコードを読めるようになってきたのではないでしょうか?

次の章からは少しずつ細いところに入っていきます!残り29問、頑張っていきましょう!

Day14.でまたお会いしましょう。