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 的视窗