Kotlin编码范式

译自Kotlin Idioms

这里是Kotlin中随机和经常使用的范式的集合。 如果你有一个最喜欢的范式,可以通过发送pull请求作出贡献。

创建DTO(POJO / POCO)

data class Customer(val name: String, val email: String)

Customer类提供了以下功能:

  • 所有属性的getter(以及在vars的情况下的setter
  • 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")
}

kv可以是任何东西。

使用范围

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
}

扩展函数

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()

创建一个单例 (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")

如果为空,则执行语句(Executing a statement if null)

val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")

如果不为空,则执行语句(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'表达式

fun test() {
    val result = try {
        count()
    } catch (e: ArithmeticException) {
        throw IllegalStateException(e)
    }

    // Working with result
}

'if'表达式

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}

以构建器风格使用返回Unit的方法(Builder-style usage of methods that return Unit)

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}

单表达式函数 (Single-expression functions)

fun theAnswer() = 42

这相当于

fun theAnswer(): Int {
    return 42
}

这可以与其他范式有效结合,导致代码更短。 例如:

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) { //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())
}

需要通用类型信息的通用函数的方便形式 (Convenient form for a generic function that requires the generic type information)

//  public final class Gson {
//     ...
//     public  T fromJson(JsonElement json, Class classOfT) throws JsonSyntaxException {
//     ...

inline fun  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
}

你可能感兴趣的:(Kotlin编码范式)