创建单例
data class Customer(val name: String, val email: String)
过滤 list[]
val positives = list.filter { x -> x > 0 }
或者
val positives = list.filter { it > 0 } //此处 it 是迭代器
list变换
例 : 有一个 User 的 list
var set :Set<User> = list.map( it.name).toSet() //此处 it 是迭代器
列表 排序
Collections.sort(datas,object:Comparator<ListGoods>{
override fun compare(o1: data?, o2: data?): Int {
return o1?.salePrice - o2?.salePrice
}
})
简化成lambada
Collections.sort(datas) { o1, o2 -> o1?.salePrice - o2?.salePrice }
列表操作
val numbers = listOf(-1, 0, 2)
val isZero: (Int) -> Boolean = { it == 0 }
numbers.any(isZero) == true
numbers.all(isZero) == false
numbers.count(isZero) == 1
numbers.find { it > 0 } == 2
集合常用操作
val numbers = listOf(1, -1, 2)
numbers.filter { it > 0 } == listOf(1, 2)
numbers.map { it * it } == listOf(1, 1, 4)
orders.flatMap { it.products }.maxBy { it.price } // order中product列表的单价最大
orders.sortedBy { it.price } // order中product列表的单价排序
orders.flatMap { it.products }.sumByDouble { it.price } // 求总价 double类型
Shop.groupCustomersByCity(): Map<City, List<Customer>> =
customers.groupBy { it.city } //返回按城市归类的列表
var (expensive, cheap) = orders.partition { it.salePrice.toFloat() > 1.0f } // 把list按条件切分为两个 list
if not null 执行代码
val data = ……
data?.let {
…… // 代码会执行到此处, 假如data不为null
}
单表达式函数
fun theAnswer() = 42
等价于
fun theAnswer(): Int {
return 42
}
使用可空布尔 需写等式,如果非空, 则与java一样
val b: Boolean? = ……
if (b == true) {
……
} else {
// `b` 是 false 或者 null
}
标准数据类 ex :
data class User(var name:Stirng,var age:Int)
equals() 等价判断是 按hashCode() ,
toString() 格式是 “User(name=John, age=42)”,
componentN() 函数 按声明顺序对应于所有属性,
copy() 函数 可以复制类的参数值
如果 数据类 需要无参构造,例如
var user :User() ;
则其参数必须有 默认值 ,例如:
data class User(var name : Stirng= "" ,var age : Int =0)
密封类
sealed class Expr
密封类用来表示受限的类继承结构 ,用法类似于 枚举类,但是一个枚举类只有一个实例,但是密封类可以有多个,
一般用于swich-case 的情况
fun eval(expr: Expr): Double = when(expr) {
is Const -> expr.number
is Sum -> eval(expr.e1) + eval(expr.e2)
NotANumber -> Double.NaN
// 不再需要 `else` 子句,因为我们已经覆盖了所有的情况
}