- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 231字
- 2021-07-23 19:05:47
There's more...
There is also a convenient way to reverse the order of an already-defined progression. We can do so with the extension function provided for the IntProgression, LongProgression, and CharProgression types, which is called reversed(). It returns new instances of progressions with a reversed order of elements. Here is an example of how to use the reversed() function:
val daysOfYear: IntRange = 1..365
for(day in daysOfYear.reversed()) {
println("Remaining days: $day")
}
The preceding for loop prints the following text to the console:
Remaining days: 365
Remaining days: 364
Remaining days: 363
…
Remaining days: 2
Remaining days: 1
The Kotlin standard library offers also another handy extension function called until(), which allows the declaration of ranges that don't include the last element. It is pretty useful when working with classes that contain internal collections and don't provide elegant interfaces to access them. A good example would be the Android ViewGroup class, which is a container for the child View type objects. The following example presents how to iterate through the next indexes of any given ViewGroup instance children in order to modify the state of each of the children:
val container: ViewGroup = activity.findViewById(R.id.container) as ViewGroup
(0 until container.childCount).forEach {
val child: View = container.getChildAt(it)
child.visibility = View.INVISIBLE
}
The until() infix function helps to make the loop conditions clean and natural to understand.
- Mastering Ext JS(Second Edition)
- Mastering NetBeans
- Python快樂(lè)編程:人工智能深度學(xué)習(xí)基礎(chǔ)
- FreeSWITCH 1.6 Cookbook
- AngularJS深度剖析與最佳實(shí)踐
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- Python應(yīng)用輕松入門
- JavaScript 程序設(shè)計(jì)案例教程
- Haxe Game Development Essentials
- Asynchronous Android Programming(Second Edition)
- Python機(jī)器學(xué)習(xí)算法: 原理、實(shí)現(xiàn)與案例
- Linux C編程:一站式學(xué)習(xí)
- ElasticSearch Cookbook(Second Edition)
- Red Hat Enterprise Linux Troubleshooting Guide
- Learning Unreal Engine Game Development