原文
这里是一些在 Kotlin 中经常使用的习语。如果你有特别喜欢的习语想要贡献出来,赶快发起 pull request 吧。
data class Customer(val name: String, val email: String)
创建 Customer 类并带有如下方法:
--为所有属性添加 getters ,如果为 var 类型同时添加 setters --
equals()
--hashCode()
--toString()
--copy()
--component1()
,component1()
, ... 参看数据类
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) { print("$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 { // compute the string }
fun String.spcaceToCamelCase() { ... } "Convert this to camelcase".spcaceToCamelCase()
object Resource { val name = "Name" }
val files = File("Test").listFiles() println(files?.size)
val files = File("test").listFiles() println(files?.size ?: "empty")
val data = ... val email = data["email"] ?: throw IllegalStateException("Email is missing!")
val date = ... data?.let{ ...//如果不为空执行该语句块 }
val data = ... val mapped = data?.let { transformData(it) } ?: defaultValueIfDataIsNull
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) } // Working with 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) { //draw a 100 pix square 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 { // ... // publicT fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException { // ... inline fun Gson.fromJson(json): T = this.fromJson(json, T::class.java)
val b: Boolean? = ... if (b == true) { ... } else { // `b` is false or null }