17611538698
webmaster@21cto.com

Kotlin 编码风格

资讯 0 2438 2017-05-29 12:01:32
随机抽取在 Kotlin 经常使用的编码风格。如果你有自己喜好的风格,可以分享给大家。

Yet-Another-Kotlin_.jpg


创建 DTOs (POJOs/POCOs)

data class Customer(val name: String, val email: String)
给 Customer 类提供下列功能:

所有属性的 getters (and setters in case of vars)
equals()
hashCode()
toString()
copy()
component1(), component2(), …, 用于所有属性 (see Data classes)
函数参数的默认值

fun foo(a: Int = 0, b: String = "") { ... }
对 list 数据进行过滤

val positives = list.filter { x -> x > 0 }

还有更短的写法:

val positives = list.filter { it > 0 }
字符串插值

println("Name $name")
实例检查

when (x) {
    is Foo -> ...
    is Bar -> ...
    else   -> ...
}
遍历 map/list 键值

for ((k, v) in map) {
    println("$k -> $v")
}
k, v 可以被任意调用

使用 ranges

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) { ... }
只读 list

val list = listOf("a", "b", "c")
第 2 段(可获 0.28 积分)
0
CY2
1周前
只读 map

val map = mapOf("a" to 1, "b" to 2, "c" to 3)
访问 map

println(map["key"])
map["key"] = value
延迟属性

val p: String by lazy {
    // compute the string
}
函数扩展

fun String.spaceToCamelCase() { ... }

"Convert this to camelcase".spaceToCamelCase()
创建单例

object Resource {
    val name = "Name"
}
If not null 速记

val files = File("Test").listFiles()

println(files?.size)
If not null 和 else 速记

val files = File("Test").listFiles()

println(files?.size ?: "empty")
在 if null 后执行语句
第 3 段(可获 0.34 积分)
0
CY2
1周前
val data = ...
val email = data["email"] ?: throw IllegalStateException("Email is missing!")
执行 if not null

val data = ...

data?.let {
    ... // execute this block if not null
}
在 when 语句中返回

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
}
第 4 段(可获 0.14 积分)
0
CY2
1周前
'if' 表达式

fun foo(param: Int) {
    val result = if (param == 1) {
        "one"
    } else if (param == 2) {
        "two"
    } else {
        "three"
    }
}
Builder 风格的方法使用并返回 Unit

fun arrayOfMinusOnes(size: Int): IntArray {
    return IntArray(size).apply { fill(-1) }
}
单表达式函数

fun theAnswer() = 42
This is equivalent to

fun theAnswer(): Int {
    return 42
}
这个可以有效的合并其他的风格,代码更加简短,例如使用 with 表达式:

fun transform(color: String): Int = when (color) {
    "Red" -> 0
    "Green" -> 1
    "Blue" -> 2
    else -> throw IllegalArgumentException("Invalid color param value")
}
第 5 段(可获 0.39 积分)
0
CY2
1周前
使用 '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 资源

val stream = Files.newInputStream(Paths.get("/some/file.txt"))
stream.buffered().reader().use { reader ->
    println(reader.readText())
}
泛型函数的便利方式
第 6 段(可获 0.33 积分)
0
CY2
1周前
//  public final class Gson {
//     ...
//     public <T> T fromJson(JsonElement json, Class<T> classOfT) throws JsonSyntaxException {
//     ...

inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)
使用允许为空的布尔类型

val b: Boolean? = ...
if (b == true) {
    ...
} else {
    // `b` is false or null
}

评论