建立DTO’s(POJO’s/POCO’s)資料類
給函數的變量增加預設值
fun test(name:String = "未知",sex:String = "男"){
}
過濾List
var result = list.filter {x -> x > 0}
//或者
var result = list.filter { it > 0 }
字元串中增加變量
val name = "小明";
println("Test Value is : $name")
執行個體檢查:
when(value){
is Foo -> ...
is Bar -> ...
else -> ...
}
周遊 map / list
for((k,v) in map){
println("$k -> $V");
}
使用 ranges :
for(i in 1..100){
//to do
}
for(i in 2:100){
//to do
}
隻讀 list
隻讀 map
通路 map
懶屬性(延遲加載):
val test:String by lazy {
//to do
}
擴充函數:
fun String.toTest(){
//to do
}
"test".toTest()
建立單例模式
Object Test{
val name = "Name"
}
如果為空則
val files = File("test").listFiles()
println(files?.size)
如果為空…否則…
val files = File("test").listFiles()
println(files?.size?:"null")
如果為空執行某操作:
val data = ...
val email = data["name"]?:throw IllegalStateException("name is null")
如果不為空執行某操作
val date = ...
data?.let{
//to do
}
傳回 when 判斷
fun transform(color:String):Int{
return when(color){
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color")
}
}
try catch 表達式
fun test(){
val result = try {
print("ok")
} catch (e:IllegalArgumentException){
print("fail")
}
}