-
通过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
-
如果一个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 } -
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
-
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
-
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
Kotlin Basic Learning - series 5
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
相关阅读更多精彩内容
- Android的KTX实现了Kotlin中的reified type parameters,这样一来,就可以不用再...
- afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...