[毎日Kotlin] Day42. Generic functions

2018.03.30

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

はじめに

毎日Kotlinシリーズです。今日で最終回!

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

問題

Generic functions | Try Kotlin

Make the following code compile by implementing a partitionTo function that splits a collection into two collections according to the predicate.

There is a partition() function in the standard library that always returns two newly created lists. You should write a function that splits the collection into two collections given as arguments. The signature of the toCollection() function from the standard library may help you.

import java.util.*

fun partitionTo() = TODO()

fun partitionWordsAndLines() {
    val (words, lines) = listOf("a", "a b", "c", "d e").
            partitionTo(ArrayList<String>(), ArrayList()) { s -> !s.contains(" ") }
    words == listOf("a", "c")
    lines == listOf("a b", "d e")
}

fun partitionLettersAndOtherSymbols() {
    val (letters, other) = setOf('a', '%', 'r', '}').
            partitionTo(HashSet<Char>(), HashSet()) { c -> c in 'a'..'z' || c in 'A'..'Z'}
    letters == setOf('a', 'r')
    other == setOf('%', '}')
}

狙い

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

GenericはKotlinでも同様に使えます。拡張関数でも使用できるので便利ですね。

解答例

fun <T, C: MutableCollection<T>> Collection<T>.partitionTo(first: C, second: C, predicate: (T) -> Boolean): Pair<C, C> {
    for (element in this) {
        if (predicate(element)) {
            first.add(element)
        } else {
            second.add(element)
        }
    }
    return Pair(first, second)
}

Javaのときとそんなに、変わらないですよね?拡張関数でも使えるので応用がものすごいききます。

ただ変性については、気をつけないといけません。こちらに詳しい資料がありますのでご覧ください。

あとがき

すべて問題を解き終わりました。やったね!

っと思ったら投稿していない問題が2つあることがわかりました。。。。

特に難問じゃないと思うので。。。番外編でやるかもしれません。。。

Kotlin力がついた実感はあるでしょうか?もっと深く学ぶ場合には、Kotlin in Actionがおすすめです!

また何かでお会いしましょう。