asReversed所在位置是kotlin.collections.asReversed,其相关用法介绍如下。

用法一

fun <T> List<T>.asReversed(): List<T>

返回原始 List 的反向只读视图。在原始列表中所做的所有更改都将反映在反向列表中。

例子:



fun main(args: Array<String>) {
//sampleStart
val original = mutableListOf('a', 'b', 'c', 'd', 'e')
val originalReadOnly = original as List<Char>
val reversed = originalReadOnly.asReversed()

println(original) // [a, b, c, d, e]
println(reversed) // [e, d, c, b, a]

// changing the original list affects its reversed view
original.add('f')
println(original) // [a, b, c, d, e, f]
println(reversed) // [f, e, d, c, b, a]

original[original.lastIndex] = 'z'
println(original) // [a, b, c, d, e, z]
println(reversed) // [z, e, d, c, b, a]
//sampleEnd
}

输出:

[a, b, c, d, e]
[e, d, c, b, a]
[a, b, c, d, e, f]
[f, e, d, c, b, a]
[a, b, c, d, e, z]
[z, e, d, c, b, a]

用法二

@JvmName("asReversedMutable") fun <T> MutableList<T>.asReversed(): MutableList<T>

返回原始可变列表的反向可变视图。在原始列表中所做的所有更改都将反映在反向列表中,反之亦然。

例子:



fun main(args: Array<String>) {
//sampleStart
val original = mutableListOf(1, 2, 3, 4, 5)
val reversed = original.asReversed()

println(original) // [1, 2, 3, 4, 5]
println(reversed) // [5, 4, 3, 2, 1]

// changing the reversed view affects the original list
reversed.add(0)
println(original) // [0, 1, 2, 3, 4, 5]
println(reversed) // [5, 4, 3, 2, 1, 0]

// changing the original list affects its reversed view
original[2] = -original[2]
println(original) // [0, 1, -2, 3, 4, 5]
println(reversed) // [5, 4, 3, -2, 1, 0]
//sampleEnd
}

输出:

[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]
[0, 1, 2, 3, 4, 5]
[5, 4, 3, 2, 1, 0]
[0, 1, -2, 3, 4, 5]
[5, 4, 3, -2, 1, 0]