习惯用法
Kotlin官网推荐的一些语法习惯
1.创建DTO
经常会有一些类只用来保存数据,这样的话在类前面加上data关键字,会为类提供下面的功能
data class Customer(val name:String,val email:String)
//实现所有属性的get set(只有var成员变量会有setter),equals,hashCode,toString,copy等方法
2.函数默认参数
fun foo(a:Int = 0,b:String = ""){...}
3.list过滤
//类似于Java8的Stream
val positives = list.filter{x-> x>0}
4.类型判断
when(x){
is A -> ...
is B -> ...
else ...
}
5.map/pair遍历
for((k,v) in map){
pringln("$k -> $v")
}
//或
for (m in map) {
println("${m.key} -> ${m.value}")
}
6.区间
for(i in 1..100){...}//闭区间
for(i in i until 100){...}//半开区间,包头不含尾
for(i in 2..10 step 2){...}
for(i in 10 downTo 1){...}
if(x in 1..10){...}
7.只读list
val list = listOf("a","b","c")
8.只读map
val map = mapOf("a" to 1, "b" to 2,"c" to 3)
9.访问map
println(map["key"])
map["key"] = value
10.延迟属性
val p:String by lazy{
//延迟计算
}
11.扩展函数
fun String.spaceToCamelCase{...}
"Convert this to camelcase".spaceToCamelCase()
//可以对原有类的方法进行扩展,在Java中是不能继承String进行扩展的,只能写Util
12.创建单例
object Resource{
val name = "Name"
}
13.if not null 缩写
val files = File("test").listFiles()
println(files?.size)
14.if not null and else 缩写
val files = File("test").listFiles()
println(files?.size ?: "empty")
15.if null执行一个语句
val values = ...
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
16.if not null
val value = ...
value?.let{
//如果value不为null,则代码会执行到这里
}
17.映射可空值(如果非空的话)
val value = ...
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
18.返回when表达式
fun transform(color:String):Int{
return when(color){
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
19.try/catch表达式
fun test(){
val result = try{
count()
}catch(e:"ArthmeticException){
throw IllegalStateException(e)
}
//使用result
}
20.if表达式
fun foo(param:Int){
val result = if(param == 1){
"one"
}else if(param == 2){
"two"
}else{
"three"
}
}
21.返回类型为 Unit 的方法的 Builder 风格用法
fun ayyayOfMinusOnes(size:Int):IntArray{
return IntArray(size).apply{fill(-1)}
}
22.单表达式函数
fun theAnswer() = 42
单表达式函数与其他习惯用法一起使用能简化代码,如
fun transform(color:String):Int = when(color){
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
23.对一个对象实例调用多个方法(with)
class Turtle{
fun penDown()
fun penUp()
fun turn(degress:Double)
fun forward(pixels:Double)
}
val myTurtle = Turtle()
with(myTurtle){
penDown()
for(i in 1..4){
forward(100.0)
turn(90.0)
}
penUp()
}
24 try with resources
val stream = Files.newInputStream(Path.get("/some/file.txt"))
stream.buffered().reader().