Idioms

kotlin習慣用法

  • 創建POJO
data class Customer(val name: String, val email: String)
  • 函數默認值
fun foo(a: Int = 0, b: String = "") {}
  • lambda表達式
list.filter{ x -> x > 0}
list.filter{ it > 0 }
  • 遍歷map
for((k,v) in map){
    println("$k -> $v")
}
  • infix 函數
infix fun Int.increase(size: Int): Int {
    return this + size
}

然后就可以通過類似1 increase 2來使用了

  • 集合的只讀創建
var list = listOf("a", "b", "c")
var map = mapOf("a" to 1, "b" to 2, "c" to 3)

這里還可以注意到to就是一個infix函數定義

  • 懶加載
val p: String by lazy { "default" }
  • 拓展函數
fun String.newFunc(): String {
    return this + "new"
}

然后就可以通過"world ".newFunc()將函數當做類的內置函數來用

  • 創建單例(?)
object Resource {
    val name = "lhyz"
}

可以這樣創建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 表達式
    val result = try {
        1
    } catch (e: ArithmeticException) {
        2
    }

同理還有if表達式也有此類表達

val result = if (true){
        "one"
    }else{
        "two"
    }
  • 使用with針對同一對象實例調用多個方法
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用法就是自動關閉的用法
可以看出use函數的定義是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()
        }
    }
}
  • 泛型函數的簡化用法(?)
inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)

總結

目前來看,特別有趣的特性主要有拓展函數,infix,inline三種函數以及lambda表達式

*不熟悉的用法使用?標記

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容