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
指向调用者