lambda 编程
一、不变集合与可变集合
listof、setof、mapof 不变集合
mutableListOf、mutableSetOf、mutableMapOf 可变集合
var a = listOf("a","b","c") var b = mutableListOf("a","b","c")
二、集合的函数式API
通过函数式API,大大减少代码量
val list = listOf("Apple","Banana","Orange","Pear","Grape","Watermelon") //1 //通过 map 操作,把一个元素映射成一个新的元素 val newList = list.map{ it.toUpperCase() } for (s in newList) { print("$s ") } //打印结果 APPLE BANANA ORANGE PEAR GRAPE WATERMELON //2 //通过 filter 筛选操作,筛选长度小于等于5的字符串 val newList = list.filter { it.length <= 5 } for (s in newList) { print("$s ") } //打印结果 Apple Pear Grape
三、java函数式API
kotlin中内部类写法与java不一样,kotlin去掉了new关键字,改用object代替
Thread{object :Runnable{
override fun run() {
}
}
}.start()
可简化为
Thread{ println("per$per") }.start()
object有两种作用:
1、对象表示式,用于修饰匿名对象,代替new 关键字
2、修饰静态类