Kotlin Koans - Builders

# Kotlin Koans
Kotlin Koans - Introduction
Kotlin Koans - Conventions
Kotlin Koans - Collections
Kotlin Koans - Properties
Kotlin Koans - Builders
Kotlin Koans - Generics

1 Function literals with receiver[ | ]

fun task(): List<Boolean> {
    val isEven: Int.() -> Boolean = { this % 2 == 0 }
    val isOdd: Int.() -> Boolean = { this % 2 != 0 }

    return listOf(42.isOdd(), 239.isOdd(), 294823098.isEven())
}

2 String and map builders[ | ]

import java.util.HashMap

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

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

3 The function apply[ | ]

fun <T> T.myApply(f: T.() -> Unit): T { f(); return this }

fun createString(): String {
    return StringBuilder().myApply {
        append("Numbers: ")
        for (i in 1..10) {
            append(i)
        }
    }.toString()
}

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

4 Builders how it works[ | ]

import Answer.*

enum class Answer { a, b, c }

val answers = mapOf<Int, Answer?>(
        1 to c, 2 to b, 3 to b, 4 to c
)
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}