Kotlin Basic Learning - 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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文是在学习和使用kotlin时的一些总结与体会,一些代码示例来自于网络或Kotlin官方文档,持续更新... 对...
    竹尘居士阅读 3,346评论 0 8
  • 《Kotin 编程思想·实战》 《Kotlin极简教程》正式上架: 点击这里 > 去京东商城购买阅读 点击这里 >...
    光剑书架上的书阅读 2,153评论 1 4
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,663评论 25 708
  • 前言 人生苦多,快来 Kotlin ,快速学习Kotlin! 什么是Kotlin? Kotlin 是种静态类型编程...
    任半生嚣狂阅读 26,294评论 9 118
  • 赵羽和葛年寿的动作很快,在沿着小路寻找珊珊无果后他们就前往周边郡县亮出自己身份寻求当时官员的帮忙,楚天佑赶到青桐县...
    杷杷阅读 3,429评论 0 7