kotlin習(xí)慣用法
- 創(chuàng)建POJO
data class Customer(val name: String, val email: String)
- 函數(shù)默認(rèn)值
fun foo(a: Int = 0, b: String = "") {}
- lambda表達(dá)式
list.filter{ x -> x > 0}
list.filter{ it > 0 }
- 遍歷map
for((k,v) in map){
println("$k -> $v")
}
- infix 函數(shù)
infix fun Int.increase(size: Int): Int {
return this + size
}
然后就可以通過類似1 increase 2
來使用了
- 集合的只讀創(chuàng)建
var list = listOf("a", "b", "c")
var map = mapOf("a" to 1, "b" to 2, "c" to 3)
這里還可以注意到to
就是一個(gè)infix函數(shù)定義
- 懶加載
val p: String by lazy { "default" }
- 拓展函數(shù)
fun String.newFunc(): String {
return this + "new"
}
然后就可以通過"world ".newFunc()
將函數(shù)當(dāng)做類的內(nèi)置函數(shù)來用
- 創(chuàng)建單例(?)
object Resource {
val name = "lhyz"
}
可以這樣創(chuàng)建val res = Resource
- 簡化空檢查
fun checkSize(arg: String?): Int {
return arg?.length ?: -1
}
fun checkSize(arg: String?): Int {
arg?.let {
return arg.length
}
return 0
}
- 返回when語句
fun transColor(color: String): Int {
return when (color) {
"R" -> 0
"G" -> 1
"B" -> 2
else -> throw IllegalAccessException()
}
}
- try/catch 表達(dá)式
val result = try {
1
} catch (e: ArithmeticException) {
2
}
同理還有if
表達(dá)式也有此類表達(dá)
val result = if (true){
"one"
}else{
"two"
}
- 使用
with
針對(duì)同一對(duì)象實(shí)例調(diào)用多個(gè)方法
class Turtle {
fun penDown() {}
fun penUp() {}
fun turn(degrees: Double) {}
fun forward(pixels: Double) {}
}
val myTurtle = Turtle()
with(myTurtle) {
//draw a 100 pix square
penDown()
for (i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
- 使用Java 7的try with resources類似方法
val stream = Files.newInputStream(Paths.get("path/to/file"))
stream.buffered().reader().use {
reader ->
print(reader.readText())
}
use用法就是自動(dòng)關(guān)閉的用法
可以看出use
函數(shù)的定義是inline fun
public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
var closed = false
try {
return block(this)
} catch (e: Exception) {
closed = true
try {
this?.close()
} catch (closeException: Exception) {
}
throw e
} finally {
if (!closed) {
this?.close()
}
}
}
- 泛型函數(shù)的簡化用法(?)
inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)
總結(jié)
目前來看昵骤,特別有趣的特性主要有拓展函數(shù)树碱,infix,inline三種函數(shù)以及l(fā)ambda表達(dá)式
*不熟悉的用法使用变秦?標(biāo)記