美文网首页kotlin程序员Kotlin编程
Kotlin入门之常用Idioms(风格、术语)

Kotlin入门之常用Idioms(风格、术语)

作者: 已迁至知乎_此不再维护 | 来源:发表于2017-05-20 15:16 被阅读24次

该文章记录了Kotlin中经常使用的Idioms集合。如果你有常用术语,欢迎作出贡献。

创建DTO数据传入对象(POJOs/POCOs)

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

上述代码提供的Customer类默认具有如下函数:

  1. getters (and setters in case of vars) for all properties
  2. equals()
  3. hashCode()
  4. toString()
  5. copy()
  6. component1(), component2(), …, for all properties

为函数形参定义默认值

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   -> ...
}

遍历配对列表(map/list)

for ((k, v) in map) {
    println("$k -> $v")
}

k,v可以被任意命名

使用范围

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")

只读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"
}

非null调用的缩写

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

println(files?.size)

非null调用,否则其他的缩写

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

println(files?.size ?: "empty")

为null执行表达式

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

非null执行

val data = ...

data?.let {
    ... // execute this block if not null
}

return表达式

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"
    }
}

Builder-style usage of methods that return Unit

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")
}

通过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's try with resources(Java7的资源尝试)

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): T = this.fromJson(json, T::class.java)

使用一个可null的Boolean类型的值

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

相关文章

  • Kotlin入门之常用Idioms(风格、术语)

    该文章记录了Kotlin中经常使用的Idioms集合。如果你有常用术语,欢迎作出贡献。 创建DTO数据传入对象(P...

  • kotlin入门潜修系列教程

    kotlin入门潜修之开门篇—kotlin是什么? kotlin入门潜修之基础篇—基础语法kotlin入门潜修之基...

  • Kotlin 学习之Idioms

    创建DTO(POJO/POCO) 该类提供给如下功能: getters(如果变量为var,则还会生成对应的sett...

  • SEM入门之常用术语

    01 / 展现量 Impressions 展现量是指在网民搜索时,如果您账户内符合网民搜索需求的关键词被触发,该关...

  • Kotlin 惯用语法

    Idioms 惯用语法 官方文档 Kotlin 惯用语法: Kotlin 中随机和经常使用的语法的集合。 创建 D...

  • kotlin入门(三)

    kotlin入门(一)kotlin入门(二)kotlin入门(三) kotlin里的 Any和Object 我们知...

  • Kotlin idioms(科特林惯用语法)

    Kotlin idioms(科特林惯用语法) 目录:1、创建DTO(POJO/POCO)(Create DTO/P...

  • Kotlin之常用操作符

    前言 熟悉Kotlin中常出现的一些操作符的用法,有助于我们快速入门Kotlin,下面将列举Kotlin中常用的一...

  • kotlin入门(二)

    kotlin入门(一)kotlin入门(二)kotlin入门(三) 注意: 部分代码来自 https://try....

  • Kotlin编码范式

    译自Kotlin Idioms 这里是Kotlin中随机和经常使用的范式的集合。 如果你有一个最喜欢的范式,可以通...

网友评论

    本文标题:Kotlin入门之常用Idioms(风格、术语)

    本文链接:https://www.haomeiwen.com/subject/mlrpxxtx.html