Kotlin Koans 37 String and map builders

String and map builders (Playground)

Description

Extension function literals are very useful for creating builders, e.g.:

拡張関数リテラルは、ビルダーを作成するのに非常に有用です。例:

fun buildString(build: StringBuilder.() -> Unit): String {
val stringBuilder = StringBuilder()
stringBuilder.build()
return stringBuilder.toString()
}

val s = buildString {
this.append("Numbers: ")
for (i in 1..3) {
// 'this' can be omitted
append(i)
}
}

s == "Numbers: 123"

Add and implement the function 'buildMutableMap' with one parameter (of type extension function) creating a new HashMap, building it and returning it as a result. The usage of this function is shown below.

新しい HashMap を作成、構築、結果として返却する、(拡張関数型の)1つの引数をとる 'buildMutableMap' 関数を追加実装してください。以下に、この関数の使用方法を示します。

Code

import java.util.HashMap

fun <K, V> buildMutableMap(build: HashMap<K, V>.() -> Unit): Map<K, V> {
val map = HashMap<K, V>()
map.build()
return map
}

fun usage(): Map<Int, String> {
return buildMutableMap {
put(0, "0")
for (i in 1..10) {
put(i, "$i")
}
}
}

← Blog