一些在 Kotlin 中广泛使用的语法习惯,如果你有更喜欢的语法习惯或者风格,建一个 pull request 贡献给我们吧!
data class Customer(val name: String, val email: String)
会为 Customer
类提供以下功能:
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 }
println("Name $name")
when (x) {
is Foo //-> ……
is Bar //-> ……
else //-> ……
}
for ((k, v) in map) {
println("$k -> $v")
}
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 {
// 计算该字符串
}
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")
val values = ……
val email = values["email"] ?: throw IllegalStateException("Email is missing!")
val emails = …… // 可能会是空集合
val mainEmail = emails.firstOrNull() ?: ""
val value = ……
value?.let {
…… // 代码会执行到此处, 假如data不为null
}
val value = ……
val mapped = value?.let { transformValue(it) } ?: defaultValueIfValueIsNull
fun transform(color: String): Int {
return when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("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"
}
}
Unit
的方法的 Builder 风格用法fun arrayOfMinusOnes(size: Int): IntArray {
return IntArray(size).apply { fill(-1) }
}
fun theAnswer() = 42
等价于
fun theAnswer(): Int {
return 42
}
单表达式函数与其它惯用法一起使用能简化代码,例如和 when{: .keyword } 表达式一起使用:
fun transform(color: String): Int = when (color) {
"Red" -> 0
"Green" -> 1
"Blue" -> 2
else -> throw IllegalArgumentException("Invalid color param value")
}
with
)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())
}
// 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)
val b: Boolean? = ……
if (b == true) {
……
} else {
// `b` 是 false 或者 null
}