譯自Kotlin Idioms
這里是Kotlin中隨機(jī)和經(jīng)常使用的范式的集合。 如果你有一個(gè)最喜歡的范式姚垃,可以通過發(fā)送pull請(qǐng)求作出貢獻(xiàn)。
創(chuàng)建DTO(POJO / POCO)
data class Customer(val name: String, val email: String)
為Customer
類提供了以下功能:
- 所有屬性的
getter
(以及在vars
的情況下的setter
) equals()
hashCode()
toString()
copy()
-
component1()
盼忌,component2()
积糯,...,對(duì)所有屬性(參見數(shù)據(jù)類(Data classes) )
函數(shù)參數(shù)的默認(rèn)值
fun foo(a: Int = 0, b: String = "") { ... }
過濾一個(gè)列表
val positives = list.filter { x -> x > 0 }
或者谦纱,甚至更短:
val positives = list.filter { it > 0 }
字符串插值
println("Name $name")
實(shí)例檢查
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
遍歷成對(duì)的映射/列表
for ((k, v) in map) {
println("$k -> $v")
}
k
看成, v
可以是任何東西。
使用范圍
for (i in 1..100) { ... } // closed range: includes 100
for (i in 1 until 100) { ... } // half-open range: does not include 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")
只讀映射
val map = mapOf("a" to 1, "b" to 2, "c" to 3)
訪問映射
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)建一個(gè)單例 (singleton)
object Resource {
val name = "Name"
}
如果非空的縮寫 (If not null shorthand)
val files = File("Test").listFiles()
println(files?.size)
如果不是空跨嘉,否則的縮寫 (If not null and else shorthand)
val files = File("Test").listFiles()
println(files?.size ?: "empty")
如果為空川慌,則執(zhí)行語句(Executing a statement if null)
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
如果不為空,則執(zhí)行語句(Execute if not null)
val data = ...
data?.let {
... // execute this block if not null
}
如果不為空祠乃,則映射可空值 (Map nullable value if not null)
val data = ...
val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
使用when語句返回 (Return on when statement)
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)
}
// Working with result
}
'if'表達(dá)式
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
以構(gòu)建器風(fēng)格使用返回Unit的方法(Builder-style usage of methods that return Unit)
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
單表達(dá)式函數(shù) (Single-expression functions)
fun theAnswer() = 42
這相當(dāng)于
fun theAnswer(): Int {
return 42
}
這可以與其他范式有效結(jié)合梦重,導(dǎo)致代碼更短。 例如:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
在對(duì)象實(shí)例上調(diào)用多個(gè)方法('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("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
需要通用類型信息的通用函數(shù)的方便形式 (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)
使用可空的布爾值 (Consuming a nullable Boolean)
val b: Boolean? = ...
if (b == true) {
...
} else {
// `b` is false or null
}