31DaysOfKotlin-series 4

  1. Android的KTX实现了Kotlin中的reified type parameters,这样一来,就可以不用再传递class的参数给我们的函数,比如:

    // the old way
    var alarmManager = context.getSystemService(AlarmManager::class.java)
    
    // the reified way
    var alarmManager: AlarmManager = context.systemService()
    // or
    var alarmManager = context.systemService<AlarmManager>()
    
    // the magic from Android KTX... with "real" type T
    inline fun <reified T> Context.systemService() = getSystemService(T::class.java)
    
    //previously 
    fun <T> TreeNode.findParentOfType(clazz: Class<T>): T? {
        var p = parent
        while (p != null && !clazz.isInstance(p)) {
            p = p.parent
        }
        @Suppress("UNCHECKED_CAST")
        return p as T?
    }
    // call
    treeNode.findParentOfType(MyTreeNode::class.java)
    
    // actually we want pass a type to this funciton, like:
    treeNode.findParentOfType<MyTreeNode>()
    // enable this, try use reified modifier
    inline fun <reified T> TreeNode.findParentOfType(): T? {
        var p = parent
        while (p != null && p !is T) {
            p = p.parent
        }
        return p as T?
    }
    

    Inline Functions and Reified Type Parameters - Kotlin Programming Languagekotlinlang.org

  2. 通过关键字“by”可以将你的工作委托给另外一个class,在前面系列的lazy中其实已经提到过了。

    class MyAnimatingView: View(/*...*/) {
        // delegated property. Uses the getter and setter defined in InvalidateDelegeate
        var foregroundX by InvalidateDelegate(0f)
    }
    
    // A View Delegate which invalidates View.postInvalidateOnAnimation when set.
    class InvalidateDelegate<T: Any>(var value: T) {
        operator fun getValue(thisRef: View, property: KProperty<*>) = value
        operator fun setValue(thisRef: View, property: KProperty<*>, value: T) {
            this.value = value
            this.Ref.postInvalidateOnAnimation()
        }
    }
    

    Delegated Properties - Kotlin Programming Languagekotlinlang.org

  3. No more Util classes。可以通过“extension functions”实现。在你想要添加方法的前面放上class的名字即可。比如:

    // Exten String with toUri
    inline fun String.toUri(): Uri = Uri.parse(this)
    
    // And call it on any String!
    val myUri = "www.developer.android.com".toUri()
    

    android/android-ktxandroid-ktx - A set of Kotlin extensions for Android app development.github.com

  4. 在Android里面如果我们要实现一个从Drawable转换到Bitmap,就会需要一系列的步骤。但Android KTX提供了一些方法,让你的代码更加的简洁。(可以查看graphics package)

    // get a drawable from resources
    val myDrawable = ContextCompat.getDrawable(context, R.drawable.icon)
    
    //convert the drawable to a bitmap
    val bitmap = myDrawable.toBitmap()
    

    android/android-ktxandroid-ktx - A set of Kotlin extensions for Android app development.github.com

  5. Sequence和Iterator很像,但Sequence其实perform lazily当你需要的时候,比如调的它的时候,但是Iterator更像是马上执行返回另外一个Iterable,如:

    // Sequence<T>.map { ... }
    val seq = sequenceOf(1, 2)
    val seqMapped: Sequence<Int> = seq.map { print("$it "); it * it } // intermediate
    print("before sum ")
    val sum = seqMapped.sum() // terminal
    
    // prints:
    // before sum 1 2
    
    // Iterable<T>.map { ... }
    val lst = listOf(1, 2)
    val lstMapped: List<Int> = lst.map { print("$it "); it * it }
    print("before sum ")
    val sum = lstMapped.sum()
    
    // prints:
    // 1 2 before sum
    
    val sequence = List(50) {it * 5}.asSequence
    sequence.map {it * 2}         // lazy(iterate 1 element at a time)
    		.filter {it % 3 == 0} // lazy(iterate 1 element at a time)
    		.map {it + 1}		  // lazy(iterate 1 element at a time)
    		.toList {}			  // eager (iterate all elemnts)
    

    kotlin.sequences - Kotlin Programming Languagekotlinlang.org

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值