Kotlin語言編程技巧集

空語句

Kotlin 語言中的空語句有android

  • {}
  • Unit
when (x) {
    1 -> ...
    2 -> ...
    else -> {}
    // else -> Unit
}

When 表達式

使用不帶判斷條件的 when 表達式來改寫多路分支api

val v = if (x < y) 1 else if (x == y) 2 else 3

val v = when {
    x < y -> 1
    x == y -> 2
    else -> 3
}

使用帶判斷條件的 when 表達式來模擬模式匹配app

val v = if (x == 1) 1 else if (x == 2) 3 else 5

val v = when (x) {
    1 -> 1
    2 -> 3
    else -> 5
}

?. 與 ?:

// n的值爲a,b,c,4當中第一個不是null的數
val n = a ?: b ?: c ?: 4
a b c n
1 / / 1
null 2 / 2
null null 3 3
null null null 4
// n的值爲a.b.c,條件是a,a.b,a.b.c都不是null。不然n的值爲4。
val n = a?.b?.c ?: 4
a a.b a.b.c n
null / / 4
!= null null / 4
!= null != null null 4
!= null != null 3 3

使用解構聲明來聲明兩個帶值的變量

var (a, b) = listOf(1, 2) // a == 1, b == 2
var (a, b) = Pair(1, 2) // a == 1, b == 2
var (a, b) = 1 to 2 // a == 1, b == 2

let

the tldr; on Kotlin’s let, apply, also, with and run functionsless

// Calls the specified function [block] with `this` value as its argument and returns its result.
public inline fun <T, R> T.let(block: (T) -> R): R = block(this)

調用代碼塊,代碼塊中調用方 this 爲參數 it,返回代碼塊的結果。ide

// using 'let' to convert from one type to another
val answerToUniverse = strBuilder.let {
    it.append("Douglas Adams was right after all")
    it.append("Life, the Universe and Everything")
    42
}
// using 'let' to only print when str is not null
str?.let { print(it) }

apply

// Calls the specified function [block] with `this` value as its receiver and returns `this` value.
public inline fun <T> T.apply(block: T.() -> Unit): T { block(); return this }

調用代碼塊,代碼塊中調用方 this 爲隱式調用方 receiver,返回調用方 this。函數

// old way of building an object
val andre = Person()
andre.name = "andre"
andre.company = "Viacom"
andre.hobby = "losing in ping pong"
// after applying 'apply' (pun very much intended)
val andre = Person().apply {
    name = "Andre"
    company = "Viacom"
    hobby = "losing in ping pong"
}

also

// Calls the specified function [block] with `this` value as its argument and returns `this` value.
public inline fun <T> T.also(block: (T) -> Unit): T { block(this); return this }

調用代碼塊,代碼塊中調用方 this 爲參數 it,返回調用方 this 。post

// transforming data from api with intermediary variable
val rawData = api.getData()
Log.debug(rawData)
rawData.map {  /** other stuff */  }
// use 'also' to stay in the method chains
api.getData()
    .also { Log.debug(it) }
    .map { /** other stuff */ }

with

// Calls the specified function [block] with the given [receiver] as its receiver and returns its result.
public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

調用代碼塊,代碼塊中指定參數爲隱式調用方 receiver,返回代碼塊的結果。ui

// Every Android Developer ever after Wednesday May 17th 2017
    messageBoard.init(「https://url.com」)
    messageBoard.login(token)
    messageBoard.post("Kotlin’s a way of life bro")

// using 'with' to avoid repetitive references to identifier
with(messageBoard) {
    init(「https://url.com」)
    login(token)
    post(「Kotlin’s a way of life bro")
}

run

// Calls the specified function [block] with `this` value as its receiver and returns its result.
public inline fun <T, R> T.run(block: T.() -> R): R = block()

調用代碼塊,代碼塊中調用方 this 爲隱式調用方 receiver,返回代碼塊的結果。this

// GoT developers after season 7
aegonTargaryen = jonSnow.run {
    makeKingOfTheNorth()
    swearsFealtyTo(daenerysTargaryen)
    realIdentityRevealed(「Aegon Targaryen」)
}

let, apply, also, with & run

代碼塊/函數 let apply also with run
參數或調用方 this 爲隱式調用方 receiver
調用方 this 爲參數 it
返回調用方 this
返回代碼塊的結果

takeIf / takeUnless

difference between kotlin also, apply, let, use, takeIf and takeUnless in Kotlinurl

// Returns this value if it satisfies the given predicate or null, if it doesn't.
inline fun <T> T.takeIf(predicate: (T) -> Boolean): T? = if (predicate(this)) this else null
// Returns this value if it does not satisfy the given predicate or null, if it does.
inline fun <T> T.takeUnless(predicate: (T) -> Boolean): T? = if (!predicate(this)) this else null

takeIf:調用方 this 若是符合某個條件則返回調用方 this,不然返回 null。
takeUnless:調用方 this 若是不符合某個條件則返回調用方 this,不然返回 null。

println(myVar.takeIf { it is Person } ?: "Not a person!")
println(myVar.takeUnless { it is Person } ?: "It's a person!")
相關文章
相關標籤/搜索