继续………..
1,智能创建JavaBean对象
在写java 时,创建一个JavaBean对象,我们总是要写很多的get,set方法,去设置或取对象的值,在Kotlin的世界里,data class Customer(val name: String, val email: String)
只要在class 关键词前加data 字段,Kotlin就会为我们自动生成get,set方法,当然还有如下方法也替我们实现好了,是不是很方便呢。。。
1,getters (and setters in case of vars)
2,equals()
3,hashCode()
4,toString()
5,copy()
2,方法支持提供默认值
fun foo(a: Int = 0, b: String = "") { ... }
在写Java时, 难免会写很多的重载函数,去设置一定默认值,Kotlin这个特性,可以替我们节省时间写更多的代码。
3,集合过滤
val positives = list.filter { x -> x > 0 }
或
val positives = list.filter { it > 0 }
4,遍历Map
for ((k, v) in map) {
println("$k -> $v")
}
5,When关键字
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
6,try ,catch 的使用
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// Working with result
}
7,else if 的返回值
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}