Android Kotlin 委託屬性

不知道如何測試下列語法可以參考如何使用Android Studio 測試資料?

  1. 變數委託
  2. lazy懶加載用法+String.split
  3. 可觀察屬性observable
  4. 委託內建map
  5. 本地委託屬性,此方法可以減少加載
  6. 委託屬性,唯獨與可讀可寫的方法
  7. 將舊方法棄用

  • 1. 變數委託
  • class Example {
        var p: String by Delegate()
    }
    class Delegate {
        //重寫get
        operator fun getValue(
            thisRef: Any?,
            property: KProperty
        ): String {
            return "$thisRef, thank you for delegating " +
                    "${property.name} to me!"
        }
        //重寫set
        operator fun setValue(
            thisRef: Any?,
            property: KProperty,
            value: String
        ) {
            println("$value has been assigned to " +
                    "${property.name} in $thisRef.")
        }
    }
    @Test
    fun test() {
        val e = Example()
        //打印com.xxxx.ExampleUnitTest$Example@157632c9,
        //thank you for delegating 'p' to me!
        println(e.p)
    
        //打印123 has been assigned to 'p' in
        //com.xxxx.ExampleUnitTest$Example@157632c9.
        e.p = "123"
    }
    

  • 2. lazy懶加載用法+String.split
  • private val data: String by lazy {
        println("init data")
        "init data"
    }
    @Test
    fun test() {
        //呼叫這行時,打印 init data
        val array = data.split(" ")
    
        //呼叫這行時打印 array = [init, data], array.size 2
        println("array = $array, array.size ${array.size}")
    }
    

  • 3. 可觀察屬性observable
  • //可觀察屬性observable
    class User {
        //初始值是
        var dataName: String by Delegates
            .observable("") {
                prop, old, new ->
            println("${prop.name} $old -> $new")
        }
    }
    @Test
    fun test() {
        val user = User()
        user.dataName = "first"
        //打印dataName  -> first
        
        user.dataName = "second"
        //打印dataName first -> second
    }
    

  • 4. 委託內建map
  • //唯讀的map
    class User(
        map: Map
    ) {
        val name: String by map
        val age: Int     by map
    }
    //可讀可寫
    class MutableUser(
        map: MutableMap
    ) {
        var name: String by map
        var age: Int     by map
    }
    private val user = User(
        mapOf(
            "name" to "John Doe",
            "age"  to 25
        )
    )
    private val mutableUser = MutableUser(
        mutableMapOf(
            "name" to "John Doe",
            "age"  to 25
        )
    )
    @Test
    fun test() {
        println(user.name) 
        // 打印 John Doe
        
        println(user.age)  
        // 打印 25
        println(mutableUser.name) 
        // 打印 John Doe
        
        println(mutableUser.age)  
        // 打印 25
    }
    

  • 5. 本地委託屬性,此方法可以減少加載
  • interface I {
        fun doSomething()
        fun isValid(): Boolean
    }
    private fun example(
        someCondition: Boolean, 
        computeFoo: () -> I
    ) {
        //當someCondition == true,才會加載computeFoo
        val memoizedFoo by lazy(computeFoo)
        if (someCondition && memoizedFoo.isValid()) {
            memoizedFoo.doSomething()
        }
    }
    private val callback = object : I {
        override fun doSomething() {
            println("doSomething")
        }
        override fun isValid(): Boolean {
            return false
        }
    }
    @Test
    fun test() {
        example(true) {
            println("process data")
            callback
        }
    }
    

  • 6. 委託屬性,唯讀與可讀可寫的方法
  • fun resourceDelegate(): ReadWriteProperty =
        object : ReadWriteProperty {
            var curValue = 0
            override fun getValue(
                thisRef: Any?, 
                property: KProperty
            ): Int = curValue
            override fun setValue(
                thisRef: Any?, 
                property: KProperty, 
                value: Int
            ) {
                curValue = value
            }
        }
    val readOnly: Int by resourceDelegate()  
    // ReadWriteProperty as val
    var readWrite: Int by resourceDelegate()
    @Test
    fun test() {
        readOnly = 0//錯誤
        readWrite = 0//正常
    }
    

    7. 將舊方法棄用

    class MyClass {
        //將舊的參數棄用方式
        var newName: Int = 0
        @Deprecated("Use 'newName' instead", 
            ReplaceWith("newName")
        )
        var oldName: Int by this::newName
    }
    @Test
    fun test() {
        val myClass = MyClass()
        // Notification: 'oldName: Int' is deprecated.
        // Use 'newName' instead
        myClass.oldName = 42
        println(myClass.newName) // 42
    }
    


    上面皆是版本ext.kotlin_version = “1.5.0″測試的


    更多相關可以參考這裡


    相關文章

    Android Kotlin 基本語法1Android Kotlin 基本語法2
    1. var 可變變數
    2. val 不可變更參數
    3. Array 用法
    4. ArrayList 用法
    5. List的filter、sort、map、forEach
    6. when 用法
    7. fun 函式用法
    8. if 表達式
    9. for 表達式
    10. 擴充函數(自定義函式)
    1. 操作符重載
    2. 資料區間用法
    3. map使用方法
    4. 內部靜態變數
    5. 靜態變數
    6. 當資料如果是?型態宣告
    7. 資料使用!!,強制將Int?轉Int
    8. data class用法
    9. 強制轉型
    10. run、with、apply、also用法
    Android Kotlin 基本語法3Android Kotlin 基本語法4
    1. class多建構式
    2. 內部class用法
    3. interface
    4. enum class 用法
    5. sealed class 用法
    6. open 用法
    1. 為基礎類型新增函式
    2. Abstract技巧使用
    3. throw使用方法
    4. 利用let特性處理資料型態?
    5. 快速初始化Array
    6. 快速將兩個資料交換
    7. 自定義待處理的fun
    8. 幫loop設定標籤
    Android Kotlin Classes and Objects-1Android Kotlin Classes and Objects-2
    1. 多個class與執行順序
    2. init與constructor執行優先序
    3. open繼承與禁止繼承
    4. 不同的寫法,影響override能不能改變值
    5. 繼承與當前Class執行順序
    6. 由inner class去找parent的super
    7. 繼承多個class時,選擇指定的Parent
    8. private protected public internal修飾符差異
    1. 幫List新增swap功能
    2. 擴充外加函式,幫助程式簡化
    3. T,多類型引入
    4. T搭配in、out使用
    5. 1個對象的object用法
    6. 類型別名
    7. 內聯類
    8. 委託

    訂閱Codeilin的旅程,若有最新消息會通知。

    廣告

    發表迴響

    在下方填入你的資料或按右方圖示以社群網站登入:

    WordPress.com 標誌

    您的留言將使用 WordPress.com 帳號。 登出 /  變更 )

    Facebook照片

    您的留言將使用 Facebook 帳號。 登出 /  變更 )

    連結到 %s

    透過 WordPress.com 建置的網站.

    向上 ↑

    %d 位部落客按了讚: