官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 康保县| 罗平县| 四川省| 卓资县| 昌江| 凤山县| 安国市| 象山县| 分宜县| 临江市| 泊头市| 临江市| 德令哈市| 濮阳县| 海淀区| 洛隆县| 新乡县| 临西县| 即墨市| 渭源县| 广南县| 峨边| 西林县| 河北省| 涪陵区| 莱芜市| 肥东县| 昭觉县| 乌兰察布市| 梅州市| 茂名市| 太谷县| 榕江县| 东阿县| 磐石市| 甘谷县| 马关县| 横峰县| 哈巴河县| 宜丰县| 张家川|