习惯用语
这里是一些在 Kotlin 中经常使用的习语。如果你有特别喜欢的习语想要贡献出来,赶快发起 pull request 吧。
dataclassCustomer(valname:String,valemail:String)
给 Customer 类提供如下方法:
--为所有属性添加 getters ,如果为 var 类型同时添加 setters --equals()--haseCode()--toString()--copy()--component1(),component1(), ... 参看数据类
funfoo(a:Int=0,b:String="") {...}
valpositives=list.filter { x->x>0}
或者更短:
valpositives=list.filter { it>0}
println("Name$name")
when(x) {isFoo->...isBar->...else->...}
for((k, v)inmap) {print("$k->$v")}
k,v 可以随便命名
for(iin1..100) {...}//闭区间: 包括100for(iin1until100) {...}//半开区间: 不包括100for(xin2..10step2) {...}for(xin10downTo1) {...}if(xin1..10) {...}for(iin1..100) {...}for(iin2..10) {...}
val list = listOf("a", "b", "c")
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
println(map["key"])
map["key"] = value
valp:Stringbylazy{//生成string的值}
funString.spcaceToCamelCase() {...}"Convert this to camelcase".spcaceToCamelCase()
objectResource{valname="Name"}
valfiles=File("Test").listFiles()println(files?.size)
valfiles=File("test").listFiles()println(files?.size ?:"empty")
valdata=...valemail=data["email"] ?:throwIllegalStateException("Email is missing!")
valdate=...data?.let{...//如果不为空执行该语句块}
funtransform(color:String):Int{returnwhen(color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value")}}
funtest() {valresult=try{count()}catch(e:ArithmeticException) {throwIllegaStateException(e)}//处理 result}
funfoo(param:Int){valresult=if(param==1) {"one"}elseif(param==2) {"two"}else{"three"}}
funarrOfMinusOnes(size:Int):IntArray{returnIntArray(size).apply{ fill(-1) }}
funtheAnswer()=42
与下面的语句是等效的
funtheAnswer():Int{return42}
这个可以和其它习惯用语组合成高效简洁的代码。譬如说 when 表达式:
funtransform(color:String):Int=when(color) {"Red"->0"Green"->1"Blue"->2else->throwIllegalArgumentException("Invalid color param value")}
classTurtle{funpenDown()funpenUp()funturn(degrees:Double)funforward(pixels:Double)}valmyTurtle=Turtle()with(myTurtle) {//画一个100像素的正方形penDown()for(iin1..4) { forward(100.0)turn(90.0)}penUp()}
valstream=Files.newInputStream(Paths.get("/some/file.txt"))stream.buffered().reader().use { reader->println(reader.readText())}
//public final class Gson {//...//public T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException {//...inlinefun Gson.fromJson(json):T=this.fromJson(json, T::class.java)
valb:Boolean?=...if(b==true) {...}else{//`b` 是false或者null}