地址:http://kotlinlang.org/docs/reference/idioms.html
这篇文章是 Kotlin 中经常使用的 习语 的集合。如果你有更喜欢的,欢迎通过 Pull request 分享
data class Customer(val name: String, val email: String)
这条语句创建了一个有如下特性的 Customer
类
– 为所有属性创建 getters,如果 该属性是 var 的话,也创建 setters 属性
– equals()
– hashCode()
– toString()
– copy()
– 为所有属性创建 component1()
, component2()
,…,详情查看Data classes
fun foo(a: Int = 0, b: String = "") {...}
val positives = list.filter {x -> x > 0 }
或者更简单
val positives = list.filter { it > 0 }
用 $ 符号
println("Name $name")
when (x) {
is Foo -> ...
is Bar -> ...
else -> ...
}
for ((k, v) in map) {
println("$k -> $v")
}
for (i in 1..100) {...} // 闭区间,包括 100
for (i in 1 until 100) {...} // 半开区间,不包括 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 {
// 定义 string
}
fun String.spaceToCamelCase() { ... }
"Convert this to camelcase".spaceToCamelCase();
object Resource {
val name = "Name"
}
一个问号:?
val files = File("Test").listFiles()
println(files?.size)
问号和冒号:?:
val files = File("Test").listFiles()
println(files?.size ?: "empty")
我的发现:上面的语句等价于
if (files != null) {
println(files.size())
} else {
println("empty");
}
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
我的发现:上面的语句等价于
if (data[""] == null) {
return throw IllegalStateException("Email is missing!");
} else {
else data[""]
}
val data = ...
data?.let {
... // 若 data 不为 null,则执行这个代码块
}
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentExcetion("Invalid color param value")
}
}
fun test() {
val result = try {
count()
} catch (e: ArithmeticException) {
throw IllegalStateException(e)
}
// 操作 result
}
fun foo(param: Int) {
val result = if (param == 1) {
"one"
} else if (param == 2) {
"two"
} else {
"three"
}
}
fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
fun theAnswer() = 42
这个等价于
fun theAnswer(): Int {
return 42
}
这可以更高效地和其他习语一起使用,写出更简洁的代码。比如 和 when 表达式一起使用
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
class Turtle {
fun penDown()
fun penUp()
fun turn(degrees: Double)
fun forward(pixels: Double)
}
val myTurtle = Turtle()
with(myTurtle) { // 画一个 100 像素的正方形
penDown()
for (i in 1..4) {
forward(100.0)
turn(90.0)
}
penUp()
}
val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
println(reader.readText())
}
// Java 的定义
// public final class Gson {
// ...
// public <T> T fromJson(JsonElement json, Class<T> classOfT) throws
// JsonSyntaxException {
// ...
inline fun T: Any> Gson.fromJson(): T = this.fromJson(json, T::class.java)
val b: Boolean? = ...
if (b == true) {
} else {
// b 为 空 或者 false 时执行这个分支
}