习惯用语
- 习语
- 创建DTOs(POJOs/POCOs)数据类
- 函数默认参数
- 过滤list
- 字符串插值
- 实例检查
- 遍历map/list键值对
- 使用ranges
- 只读list
- 只读map
- 访问map
- 懒属性(延迟加载)
- 扩展函数
- 创建单例模式
- 如果不为空则…的简写
- 如果不为空否则的简写
- 如果生命为空执行某操作
- 如果不为空执行某操作
- 如果不空则映射(Map nullable value if not null)
- 返回when判断
- try-catch表达式
- if表达式
- 使用生成器模式返回Unit
- 单表达式函数
- 利用with调用一个对象实例的多个方法
- Java 7s try with resource
- 需要泛型类型信息的泛型函数的简便形式
- 消费一个可能为空的布尔值
习语
创建DTOS(POJOs/POCOs)数据类
//数据类
data class Customer(val name:String,val email:String)
数据类拥有以下功能:
- 所有属性的getter和setter(对于var定义的还有setter)
- equals()
- toString()
- Copy()
- 所有属性的component1()、componen2()…等等(参见数据类)
函数的默认参数
fun test(a:Int,b:Int=1,c:String=""){}
过滤list
val nums= listOf("wyc","lyb","zyf")
val positives=nums.filter { x->x.length>0 }
//另一种写法
val positives=nums.filter{it.length>0}
字符串内插
val name="wyc"
println("name $name")
类型判断
when(x){
is Foo ->"" //Foo是类
is Bar -> "bar" //Bar是类
else -> "什么都是"
}
遍历map/pair型list
for((K,V)in map){
println("key is $K , value is $V")
}
这里面涉及到一个扩展函数的定义
使用区间
for(i in 1..100){...}//闭区间 包含100
for(i in 1 untils 100){...}//开区间 不包含100
for(i in 1..10 step 2){...}//僭越区间,每次跳2
for(i in 10 downTo 1){...}//递减区间 从10到1
if(x in 1..10){...}//判断区间 判断参数是否属于某个区间
只读list
val list=listOf("wyc","cyw","xy")
只读map
//只读map
val nameMap= mapOf("wyc" to "Android","cy" to "php")
访问map
println(nameMap["wyc"])
延迟属性
val p:String by lazy{
//只在用到p的时候,p才初始化
}
扩展函数
fun String.spaceToCame(){...}
//这时候如果调用spaceToCame方法,需要两个String类型的数据
"wyc".spaceToCame()
创建单例
//创建单例,注意单例不能是内部类,或者类中属性
object ResourceTest{
val name="Name"
}
println(ResourceTest.name)
if not null 缩写
val files=File("Test").listFiles()
println(files?.size)
if not null and else缩写
val files=File("Test").listFiles()
println(files?.size ?: "empty")
if null 执行一个语句
//if null 执行一个语句
val mapTest= mapOf("wyc" to 1,"cy" to 2)
val num=mapTest["wwyc"]?:throw IllegalArgumentException("wc")
在可能会空的集合取第一个元素
val emailsTest:List<String> = listOf<String>()
val mainName=emailsTest.firstOrNull()?:"diyige"
println(mainName)
//输出
diyige
if not null 执行代码
valuesTEst?.let {
println("it's not empty")//如果valuesTEst部位null执行下面语句
}
映射可空值
fun toUpLoadString(str:String) :String?{
return str.toUpperCase()
}
val defaultTest="forget init data"
//映射可空值
valuesTEst?.let {
toUpLoadString(it)
}?:defaultTest
返回when表达式
//返回when表达式
fun transform(color:String):Int{
return when(color){
"red" ->0
"black"->1
else -> 9
}
}
try catch 表达式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 使用 result
}
if表达式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
返回类型为Unit的方法的Builder风格用法
//返回类型为Unit的方法的Builder风格用法
fun arrayOfMinusOnes(size:Int):IntArray{
return IntArray(size).apply { fill(-1) }
}
val arrayTest=arrayOfMinusOnes(5)
arrayTest.forEach {
println(it)
}
单表达式函数
fun theAnswer()=42
等价于
fun theAnswer():Int{return 42}
单表达式与其他惯用用法一起可以简化代码量
例如和when一起
// 单表达式
fun transformT(color:String):Int= when(color){
"red" ->0
"black"->1
else -> throw IllegalArgumentException("no the same color")
}
对一个对象实例调用多个方法(with)
//对一个对象使用with
class Turtle{
fun penDown(){
println("penDown")
}
fun penUp(){
println("penUp")
}
fun turn(degree:Double){
println("turn degree $degree")
}
fun forward(pixels:Double){
println("forward pixels $pixels")
}
}
val myTurtle=Turtle()
with(myTurtle){
penDown()
for (i in 1..4){
forward(100.0)
turn(90.0)
}
penUp()
}
Java7的try with resources
//Java7获取resources
val stream= if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Files.newInputStream(Paths.get("/some/file.txt"))
} else {
TODO("VERSION.SDK_INT < O")
}
stream.buffered().reader().use {
println(it.readText())
}
对于需要泛型信息的泛型函数的适宜形式
inline fun <reified T:Any> Gson.formJson(json:JsonElement):T=
this.fromJson(json,T::class.java)
使用可空布尔 Boolean
val b:Boolean ?=true
if(b==true){
}else{
}