用Kotlin-koans学Kotlin【六】 v_builders

本文介绍了Kotlin中扩展函数的应用、类型扩展函数的实现方式,以及如何利用apply改进代码结构。通过具体示例展示了表格渲染的方法,并解析了HTML构建器的工作原理。
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指向调用者

转载于:https://juejin.im/post/59e6b18af265da431a42472e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值