val list = listOf(1, 2, 3, 4)
//acc是上次的计算结果,初始值为StringBuffer(),返回值跟初始值类型一样
val foldStrBuf = list.fold(StringBuffer()){
acc, i -> acc.append(i)
}
println(“list.fold() $foldStrBuf”)//1234
reduce
val list = listOf(1, 2, 3, 4)
val r = list.reduce() { acc, i ->
acc + i
}
println(“list.reduce() $r”)//10
fold和reduce有点递归的意思在里面,每次的结果都是基于上次的结果。
zip
val list = listOf(1, 2, 3, 4)
val array = arrayOf(2, 2)
val z = list.zip(array) { a: Int, b: Int ->
a * b
}
z.forEach {
println(it)
} // 2 4
val array2 = arrayOf(“x”, “y”)
val z2 = list.zip(array2) { a: Int, b: String ->
“ a a ab”
}
z2.forEach {
println(it)
} // 1x 2y
看源码,zip其实就是将两个集合遍历执行某个操作,只不过最终集合大小是以最小长度的那个集合为准:
public inline fun <T, R, V> Iterable.zip(other: Array, transform: (a: T, b: R) -> V): List {
val arraySize = other.size
val list = ArrayList(minOf(collectionSizeOrDefault(10), arraySize))
var i = 0
for (element in this) {
if (i >= arraySize) break
list.add(transform(element, other[i++]))
}
return list
}
集合变换应用例子:
统计文本文件中非空格字符出现的次数
import java.io.File
fun main() {
File(“build.gradle”).readText() // 1. read file
.toCharArray() // 2.
//.filter{ !it.isWhitespace() } // 3. filter white space
.filterNot(Char::isWhitespace) // 等价上面一行
.groupBy { it } //分组
.map {
it.key to it.value.size
}.let {
println(it)
}
}
SAM转换
val executor: ExecutorService = Executors.newSingleThreadExecutor()
//匿名内部类的写法
executor.submit(object : Runnable {
override fun run() {
println(“run in executor.”)
}
})
//匿名内部类简写
executor.submit(Runnable {
println(“run in executor.”)
})
//匿名内部类简写
executor.submit { println(“run in executor.”) }
kotlin中SAM目前只支持只有一个方法的java接口
fun submitRunnable(runnable: Runnable){
runnable.run()
}
submitRunnable {
println(“Hello”)
}
kotlin中SAM不支持只有一个方法的kotlin接口, 但是可以直接定义一个函数参数
下面这样写法是不行的:
interface Invokable {
fun invoke()
}
fun submit(invokable: Invokable) {
invokable.invoke()
}
//报错
submit {
println(“Hello”)
}
下面这样写法是可行的:
typealias FunctionX = ()->Unit
//函数参数传递一个lambda表达式
fun submit(block: FunctionX){
block()
}
//等价这种直接传lambda表达式的写法
//fun submit(()->Unit){
//
//}
//这样是可以的
submit {
println(“Hello啊啊啊”)
}
一个例子,添加和移除监听的正确kotlin写法:
public class EventManager {
interface OnEventListener {
void onEvent(int event);
}
private HashSet onEventListeners = new HashSet<>();
public void addOnEventListener(OnEventListener onEventListener){
this.onEventListeners.add(onEventListener);
}
public void removeOnEve
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
ntListener(OnEventListener onEventListener){
this.onEventListeners.remove(onEventListener);
}
}
使用上面的java类:
fun main() {
val eventManager = EventManager()
//匿名内部类的写法
val onEvent = EventManager.OnEventListener { event -> println(“onEvent $event”) }
//等价上面的写法
val onEvent2 = object : EventManager.OnEventListener{
override fun onEvent(event: Int) {
println(“onEvent $event”)
}
}
// DO NOT use this.
//错误的写法,这样还是一个函数类型,传到removeOnEventListener方法里不能移除,
// 还是会调用方法创建一个对象
// val onEvent3 = { event: Int ->
// println(“onEvent $event”)
// }
eventManager.addOnEventListener(onEvent)
eventManager.removeOnEventListener(onEvent)
}
DSL: 领域特定语言
如sql语言、gradle中的groovy语言等,kotlin可以方便的实现这些语言的写法
例子: 通过拼接操作生成一个html文件
import java.io.File
interface Node {
fun render(): String
}
class StringNode(val content: String): Node {
override fun render(): String {
return content
}
}
class BlockNode(val name: String): Node {
val children = ArrayList()
val properties = HashMap<String, Any>()
override fun render(): String {
return “”"<$name KaTeX parse error: Expected '}', got 'EOF' at end of input: …perties.map { "{it.key}=’KaTeX parse error: Expected 'EOF', got '}' at position 14: {it.value}'" }̲.joinToString("…{children.joinToString(""){ it.render() }}</$name>"""
}
operator fun String.invoke(block: BlockNode.()-> Unit): BlockNode {
val node = BlockNode(this)
node.block()
this@BlockNode.children += node
return node
}
operator fun String.invoke(value: Any) {
this@BlockNode.properties[this] = value
}
operator fun String.unaryPlus(){
this@BlockNode.children += StringNode(this)
}
}
fun html(block: BlockNode.() -> Unit): BlockNode {
val html = BlockNode(“html”)
html.block()
return html
}
fun BlockNode.head(block: BlockNode.()-> Unit): BlockNode {
val head = BlockNode(“head”)
head.block()
this.children += head
return head
}
fun BlockNode.body(block: BlockNode.()-> Unit): BlockNode {
val head = BlockNode(“body”)
head.block()
this.children += head
return head
}
fun main() {
//变量后面跟东西相当于传递一个lambda表达式
val htmlContent = html {