习惯用法

函数的默认参数
fun foo(a : Int , b :Int = 0){...}
过滤list
val  result  = args.filter{it > 0}
模板字符串 ,String内插
val name = "vincent"
println("my name is  $name")
类型判断
when(x){
is  Number -> ...
in 1..100 -> ...
in 1 until 100  -> ...
else -> ...
}
遍历map/pair型list
for((key ,value)  in map){
println("$key->$value")
}
只读list
val  list = listOf(1,2,3)
只读map
val  map = mapOf("a" to 1 , "b" to 2)
访问map
println(map["key"])
延迟属性
val  list  by lazy {
    listOf("1" ,"2","3")
}
扩展函数
fun  String.spaceTocamelcase(){...}
创建单例
object Resource{
  val name = "vincnet"
}
if not null 缩写
val  files = File("Test").listFIles()
println(files?.size)
if not null and else
val  files = File("Test").listFIles()
println(files?.size?:"empity")
if null 执行语句
val  list = ...
val element = list[3]?:  throw IllegalStateException(" is missing!")
在可能为空的集合中取第一个元素
val emails = ... // 可能会是空集合
val mainEmail = emails.firstOrNull() ?: ""
if not null 执行代码
list?.let{

}

你可能感兴趣的:(习惯用法)