Android经验和架构

Idioms

2017-05-23  本文已影响0人  lhyz

kotlin习惯用法

data class Customer(val name: String, val email: String)
fun foo(a: Int = 0, b: String = "") {}
list.filter{ x -> x > 0}
list.filter{ it > 0 }
for((k,v) in map){
    println("$k -> $v")
}
infix fun Int.increase(size: Int): Int {
    return this + size
}

然后就可以通过类似1 increase 2来使用了

var list = listOf("a", "b", "c")
var map = mapOf("a" to 1, "b" to 2, "c" to 3)

这里还可以注意到to就是一个infix函数定义

val p: String by lazy { "default" }
fun String.newFunc(): String {
    return this + "new"
}

然后就可以通过"world ".newFunc()将函数当做类的内置函数来用

object Resource {
    val name = "lhyz"
}

可以这样创建val res = Resource

fun checkSize(arg: String?): Int {
    return arg?.length ?: -1
}
fun checkSize(arg: String?): Int {
    arg?.let {
        return arg.length
    }
    return 0
}
fun transColor(color: String): Int {
    return when (color) {
        "R" -> 0
        "G" -> 1
        "B" -> 2
        else -> throw IllegalAccessException()
    }
}
    val result = try {
        1
    } catch (e: ArithmeticException) {
        2
    }

同理还有if表达式也有此类表达

val result = if (true){
        "one"
    }else{
        "two"
    }
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("path/to/file"))
    stream.buffered().reader().use {
        reader ->
        print(reader.readText())
    }

use用法就是自动关闭的用法
可以看出use函数的定义是inline fun

public inline fun <T : Closeable?, R> T.use(block: (T) -> R): R {
    var closed = false
    try {
        return block(this)
    } catch (e: Exception) {
        closed = true
        try {
            this?.close()
        } catch (closeException: Exception) {
        }
        throw e
    } finally {
        if (!closed) {
            this?.close()
        }
    }
}
inline fun <reified T: Any> Gson.fromJson(json): T = this.fromJson(json, T::class.java)

总结

目前来看,特别有趣的特性主要有拓展函数,infix,inline三种函数以及lambda表达式

*不熟悉的用法使用?标记

上一篇下一篇

猜你喜欢

热点阅读