小技巧

作者: 案玉璃青 | 来源:发表于2019-09-25 13:47 被阅读0次

    1. 利用 Pair 和中缀 to 函数同时初始化两个变量

    val (key, value) = 1 to 1

    toast("key=${key}, value=${value}")

    扩展:解构 —— 允许一个类去拆解,然后分别赋值。

        通过 operator 关键字声明 componentX() 函数,X代表要解构的第X(1, 2, 3...)个属性。

    如:Pair 类

    public final data class Pair<out A, out B> public constructor(first:A, second:B) : kotlin.io.Serializable /* = java.io.Serializable */ {

        public final val first:A /* compiled code */

        public final val second:B /* compiled code */

        public final operator fun component1():A { /* compiled code */ }

        public final operator fun component2():B { /* compiled code */ }

        public open fun toString(): kotlin.String { /* compiled code */ }

    }

    2. 利用 as 对 import 进来的类、函数或属性字段进行改名

    import android.content.Intent as I

    // val intent = Intent() // 报错

    val intent = I() // 此处应该用 I

    3. 对 try catch finally 封装函数

    /**

    * @exception E 异常类型

    * @return T 返回类型

    * @param something try 代码块

    * @param onCatch catch 代码块

    */

    inline fun <reified E:Exception, reified T> tryCatch(something:() -> T, onCatch:(e:E) -> T?):T?{

        return try {

            something()

        } catch (e:Exception) {

            onCatch(eas @kotlin.ParameterName(name = "e") E)

    }

    /**

    * @exception E 异常类型

    * @see T try 代码块返回值类型

    * @return Unit

    * @param something try 代码块

    * @param onCatch catch 代码块

    * @param onFinally finally 代码块

    */

    inline fun <reified E :Exception, reified T> tryCatch(noinline something:() -> T, onCatch:(e:E) -> Unit, onFinally:(t:T?) -> Unit) {

        var t:T?= null

        try {

            t= something()

        } catch (e:Exception) {

            onCatch(eas @kotlin.ParameterName(name = "e") E)

        } finally {

            onFinally(t)

        }

    }

    4. 利用代理将 map 转成对象

    类的构造器接受一个 map 实例作为参数,将 map 实例本身作为属性的委托,属性的名称应与 map 中的 key 一致。

    // 可以得到一个包含 name 和 age 属性的 class,如果要属性是可写的 var,把 Map 改为对应的 MutableMap 即可

    class User(val map: Map<String, Any>) {

        val name: String by map

        val age: Int by map

    }

    val user = User(mapOf("name" to "w", "age" to 18))

    相关文章

      网友评论

          本文标题:小技巧

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