習(xí)慣用法
一個隨機(jī)和經(jīng)常被使用的kotlin習(xí)慣用法集合。 如果你有非常喜歡的習(xí)慣用法,可以在 github 上提交你的 pull request。
創(chuàng)建 DTOs(POJOs/POCOs)
data class Customer(val name: String, val email: String)
Customer類提供以下方法:
- 所有屬性的 setter 和 getter 方法
equals()hashCode()toString()copy()-
component1(),component2(), …,
函數(shù)參數(shù)的默認(rèn)值
fun foo(a: Int = 0, b: String = "") { ... }
過濾列表
val positives = list.filter { x -> x > 0 }
另外一種更短的表達(dá)方式:
val positives = list.filter { it > 0 }
字符串插入
println("Name $name")
實例判斷
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
遍歷 map/list 的鍵值對
for ((k, v) in map) {
println("$k -> $v")
}
k,v 可以隨意定義
使用范圍
for (i in 1..100) { ... } // 閉區(qū)間: 包括 100
for (i in 1 until 100) { ... } // 半開區(qū)間: 不包括 100
for (x in 2..10 step 2) { ... }
for (x in 10 downTo 1) { ... }
if (x in 1..10) { ... }
只讀列表
val list = listOf("a", "b", "c")
只讀 map
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
訪問 map
println(map["key"])
map["key"] = value
懶屬性
val p: String by lazy {
// compute the string
}
擴(kuò)展函數(shù)
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase()
創(chuàng)建單例
object Resource {
val name = "Name"
}
非空速記
val files = File("Test").listFiles()
println(files?.size)
非空和其他速記
val files = File("Test").listFiles()
println(files?.size ?: "empty")
為空時執(zhí)行
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
非空時執(zhí)行
val data = ...
data?.let {
... // 非空時執(zhí)行的代碼塊
}
非空時 map 可為空值
val data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
滿足條件時返回結(jié)果
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
}
'try/catch' 表達(dá)式
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 處理結(jié)果
}
'if' 表達(dá)式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
使用返回 Unit 的 Builder 風(fēng)格方法
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
單一表達(dá)式函數(shù)
fun theAnswer() = 42
等同于
fun theAnswer(): Int {
return 42
}
也可以和其他習(xí)慣用法
聯(lián)合使用, 精簡代碼. 例如:使用 when 表達(dá)式:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
** 用('with')對象實例調(diào)用多個方法**
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { // 畫一個100像素的區(qū)域
penDown()
for(i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
Java 7的資源調(diào)用
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
泛型函數(shù)的簡寫
// 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)
使用可空 Boolean 值
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` 是 false 或者 null
}
生詞表
| 單詞 | 含義 |
|---|---|
| idioms | n. 成語;慣用語;方言;風(fēng)格(idiom的復(fù)數(shù)) |
| interpolation | n. 插入;篡改;填寫;插值 |
| traverse | n. 穿過;橫貫;橫木; vt. 穿過;反對;詳細(xì)研究;在…來回移動; vi. 橫越;旋轉(zhuǎn);來回移動; adj. 橫貫的 |
| shorthand | n. 速記;速記法; adj. 速記法的 |