Kotlin/慣用語法

维基教科书,自由的教学读本

慣用語法[编辑]

建立 DTO(POJO/POCO)[编辑]

data class Customer(val name: String, val email: String)

會建立 Customer 類別,並加上以下函式:

  • 所有屬性的對應 getter
    • 如果屬性是 var 會包含 setter
  • equals()
  • hashCode()
  • toString()
  • copy()
  • 所有屬性對應的 component1(), component2()⋯⋯等

參數預設值[编辑]

fun foo(a: Int = 0, b: String = "") { ... }

過濾出所有大於零的值[编辑]

val positives = list.filter { x -> x > 0 }

或者

val positives = list.filter { it > 0 }

判斷某個值有沒有出現在列表內[编辑]

if ("john@example.com" in emailsList) { ... }

反過來是

if ("jane@example.com" !in emailsList) { ... }

插入文字[编辑]

val name = "Alice"
println("Name $name")

switch/case[编辑]

when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}

遍歷整個 map[编辑]

for ((k, v) in map) {
    println("$k -> $v")
}

使用範圍(range)[编辑]

for (i in 1..100) { ... } //會包含 i = 100
for (i in 1 until 100) { ... } //不會包含 i = 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }

Read-only 列表[编辑]

val list = listOf("a", "b", "c")

Read-only map[编辑]

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

存取 map[编辑]

println(map["key"])
map["key"] = value

Lazy property[编辑]

val p: String by lazy {
    // compute the string
}

擴充函式[编辑]

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

建立單例[编辑]

object Resource {
    val name = "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")

null 時拋出例外[编辑]

val email = values["email"] ?: throw IllegalStateException("Email is missing!")

不是 null 時執行[编辑]

value?.let {
    ... // value 不是 null 時執行
}

可能為空的集合裡取出第一個元素[编辑]

val emails = ... // 可能為空
val mainEmail = emails.firstOrNull() ?: ""

Map nullable value if not null[编辑]

val value = ...

val mapped = value?.let { transformValue(it) } ?: defaultValue 
// 如果 value 或者 transformValue() 結果是 null,回傳 defaultValue

用 when 表達式回傳[编辑]

fun transform(color: String): Int {
    return when (color) {
        "Red" -> 0
        "Green" -> 1
        "Blue" -> 2
        else -> throw IllegalArgumentException("Invalid color param value")
    }
}

try/catch[编辑]

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // Working with result
}

if[编辑]

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

Builder-style usage of methods that return Unit[编辑]

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

單一表達式函式[编辑]

fun theAnswer() = 42

等同於

fun theAnswer(): Int {
    return 42
}

這種寫法可以跟其他的寫法組合起來使用,比方說

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}

Calling multiple methods on an object instance (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()
}

Configuring properties of an object (apply)[编辑]

val myRectangle = Rectangle().apply {
    length = 4
    breadth = 5
    color = 0xFAFAFA
}

Java 7's try with resources[编辑]

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}

Convenient form for a generic function that requires the generic type information[编辑]

//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json: JsonElement): T = this.fromJson(json, T::class.java)

使用可能是 null 的 Boolean 判斷[编辑]

val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // `b` 為 false 或 null 時執行
}

交換變數[编辑]

var a = 1
var b = 2
a = b.also { b = a }

TODO()[编辑]

Kotlin 內建 TODO() 函式,這個函式會拋出 NotImplementedError,可以用來標記還沒做完的事項。

fun calcTaxes(): BigDecimal = TODO("等會計部門提供資料")

IntelliJ IDEA 會讀取 TODO() 出現的位置,並自動加入其 TODO 的視窗