31DaysOfKotlin-series 5

  • Post author:
  • Post category:其他


  1. 通过Kotlin的操作符重载可以让你写kotlin变得更快,像Path,Range或者SpannableStrings允许操作符“addition”或者“substraction”等, 你可以实现自己的操作符,比如:

    /** Adds a span to the entire text. **/
    inline operator fun Spannable.plusAssign(span: Any) = 
    	setSpan(span, 0, length, SPAN_INCLUSIVE_EXCLUSIVE)
    
    //Use it like this
    val spannable = "Eureka!!!!".toSpannable()
    spannable += StyleSpan(BOLD) // Make the text bold with +=
    spannable += UnderlineSpan() // Make the text underline with +=
    


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

  2. 如果一个class有Utility的方法,请将他们添加到文件的最顶端, 在java中它们被编译成static的方法

    // Define a top-level function that creates a DataBinding Adapter for a RecyclerView
    @BindingAdapter("userItems")
    fun userItems(recyclerView: RecyclerView, list: List<User>?) {
        // update the RecyclerView with the new list
    }
    


    Basic Syntax – Kotlin Programming Languagekotlinlang.org

  3. Android KTX添加了在ViewGroup和SparseArray中添加了iterators(区别Sequences见Series 4)。定义iterator的extensions,需要使用‘operator’关键字。Foreach loops就可以使用extensions

    // Example from Android KTX
    for (view in ViewGroup) {}
    for (key in sparseArray.keyIterator()) {}
    
    // Your project
    // add an iterator to a Waterfall
    operator fun Waterfall.iterator() = // ... extend waterfall to have iterator
    for (items in waterfall) {} // now waterfall can iterate!
    


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

  4. Android使用KTX的Content Values可以让Kotlin写起来更加的简洁,也可以传入”Pair StringKey, Value>参数。

    val contentValues = contentValuesOf(
        "KEY_INT" to 1, 
        "KEY_LONG" to 2L,
        "KEY_BOOLEAN" to true,
        "KEY_NULL" to null
    )
    


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

  5. Kotlin还支持Domain Specific Language

    html {
        head {
            title {+"This is Kotlin!"}
        }
        body {
            h1 {+"A DSL defined in Kotlin!"}
            p {+"It's rather"
            	b {+"bold."}
               + "don't you think?"
            }
        }
    }
    


    Type-Safe Builders – Kotlin Programming Languagekotlinlang.org



版权声明:本文为swust_chenpeng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。