用Kotlin-koans学Kotlin【六】 v_builders

356 阅读1分钟

36. n36ExtensionFunctionLiterals

扩展函数

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

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

37. n37StringAndMapBuilders

类型扩展函数,仿照buildString实现buildMap

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

38. n38TheFunctionApply

使用apply重写上一练习中的功能

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

39. n39HtmlBuilders

products填充进表格,并设置好背景色,运行htmlDemo.kt可以预览内容

fun renderProductTable(): String {
    return html {
        table {
            tr(color = getTitleColor()) {
                td {
                    text("Product")
                }
                td {
                    text("Price")
                }
                td {
                    text("Popularity")
                }
            }
            val products = getProducts()
            for ((index,product) in products.withIndex()){
                tr {
                    td(color = getCellColor(index,0)){
                        text(product.description)
                    }
                    td (color = getCellColor(index,1)) {
                        text(product.price)
                    }
                    td (color = getCellColor(index,2)){
                        text(product.popularity)
                    }
                }
            }
        }
    }.toString()
}

40. n40BuildersHowItWorks

答案:
1:c,td是一个方法,这里的td显然是在调用
2:b,color是参数名,这里使用了命名参数
3:b,这里是个lambda表达式
4:c,this指向调用者