Kotlin把代码写少的Tips

作者: RDuwan | 来源:发表于2017-05-20 11:26 被阅读330次

    Kotlin已经被google列为Android官方的一级开发语言,此文章是在自己学习观看google io 2017 和阅读Kotlin官方文档的时候,记录下Kotlin的一些write less的Tips.

    • Tip1:定义函数
    #常规写法:
    fun sum(a: Int, b: Int): Int {
        return a + b
    }
    #Write less:
    fun sum(a:Int, b:Int) = a + b
    
    • **Tip2:使用when关键字 **
    #相对于java常规的switch case,when提供了更加灵活的方式:
    fun describe(obj: Any): String =
    when (obj) {
        1          -> "One"
        "Hello"    -> "Greeting"
        is Long    -> "Long"
        !is String -> "Not a string"
        else       -> "Unknown"
    }
    
    fun main(args: Array<String>) {
        println(describe(1))
        println(describe("Hello"))
        println(describe(1000L))
        println(describe(2))
        println(describe("other"))
    }
    
    • Tip3:for循环中使用in,step,downTo
    #组合使用in,step,downTo
    fun main(args: Array<String>) {
        for (x in 1..10 step 4) {
            print(x)
        }
        print(" - ")
        for (x in 9 downTo 0 step 3) {
            print(x)
        }
    }
    Result:159 - 9630
    
    • Tip4:使用lambda表达式来操作集合
    #在集合中使用filter,map,sortBy等关键字
    fun main(args: Array<String>) {
        val fruits = listOf("banana", "avocado", "apple", "kiwi")
        fruits
        .filter { it.startsWith("a") }
        .sortedBy { it }
        .map { it.toUpperCase() }
        .forEach { println(it) }
    }
    Result:
    APPLE
    AVOCADO
    
    • Tip5:条件语句
    when (x) {
        is Foo -> ...
        is Bar -> ...
        else   -> ...
    }
    
    • Tip6:构造只读list,map
    val list = listOf("a", "b", "c")
    val map = mapOf("a" to 1, "b" to 2, "c" to 3)
    
    • Tip7:构造单例
    object Resource {
        val name = "Name"
    }
    
    • Tip8:null情况的赋值处理
    val data = ...
    val email = data["email"] ?: throw IllegalStateException("Email is missing!")
    
    • Tip9:在return中使用when关键字
    fun transform(color: String): Int {
        return when (color) {
            "Red" -> 0
            "Green" -> 1
            "Blue" -> 2
            else -> throw IllegalArgumentException("Invalid color param value")
        }
    }
    
    • Tip10:使用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()
    }
    
    • Tip11:if else的简写方法
    #普通写法
    var max: Int
    if (a > b) {
        max = a
    } else {
        max = b
    }
    #简写
    val max = if (a > b) a else b
    
    • Tip12:成员变量的get和set方法
    var stringRepresentation: String
       get() = this.toString()
       set(value) {
           setDataFromString(value)
       }
    
    #简写get
    val isEmpty get() = this.size == 0  // has type Boolean
    
    • Tip13:重载操作符
    operator fun ViewGroup.get(index : Int): View? = getChildAt(index)
    operator fun ViewGroup.minusAssign(child: View) = removeView(child)
    operator fun ViewGroup.plusAssign(child: View) = addView(child)
    
    #重载[] -  +,你就可以使用下面的方法来操作view
    
    val views = //...
    val first = views[0]
    views -= first
    view += first
    
    • Tip14:使用inline函数
    #java的方式
    MainActivity.java
    SQLiteDatabase db = //.....
    db.beginTransacation();
    try {
        db.delete("user","first_name = ?",new String[] {"jake"};
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
    
    #kotlin的inline函数
    ##Database.kt
    inline fun SQLiteDatabase.transaction(body : () -> Unit ) {
        beginTransaction()
        try {
              body()
              setTransaction()
        } finally {
              endTransaction()
        }
    }
    ##MainActivity.kt
    val db = //....
    db.transaction = {
            db.delete("users", "first_name = ?",arrayOf("jake"))
    }
    
    • Tip15:使用Delegate来观察值变化
    private val name by Delegate.observable("jane")  {old, new, prop - >
            println("Name changed form $old to $new )
    }
    

    相关文章

      网友评论

        本文标题:Kotlin把代码写少的Tips

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