在Kotlin中asReversed()与reversed()? [英] asReversed() vs reversed() in Kotlin?

查看:262
本文介绍了在Kotlin中asReversed()与reversed()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到Kotlin有两个内置方法 reversed() asReversed()

I noticed that Kotlin has two built in methods reversed() and asReversed()

这两者之间有什么区别吗?还是他们本质上只是在做完全相同的事情?

Is there any difference between these two? or are they essentially just doing the exact same thing?

推荐答案

在Kotlin中,reverse和asReversed都有其独特的功能.

In Kotlin, both reversed and asReversed have their own unique functions.

反向函数返回一个具有反向元素顺序的列表.

The Reverse function returns a list with elements in reversed: order.

反向功能

asReversed 函数返回原始列表的反向只读视图,即,原始列表中所做的所有更改都将反映在反向列表中.

Whereas, the asReversed function returns a reversed read-only view of the original List i.e., all changes made in the original list will be reflected in the reversed one.

as反向功能

两者之间的区别在于,一旦使用了asReversed()函数,原始列表中的任何更改也将反映在反向列表中. 但是,当使用reversed()函数时,同样的结果并不成立或成立.它仅用于反向列表.

The difference between the two are that once the asReversed() function has been used, any changes in the original list will be reflected in the reversed list as well. But the same doesn't hold valid or true when the reversed() function is being used. It's merely used to reverse a list.

示例:

    val list = mutableListOf(0, 1, 2, 3, 4, 5)

    val asReversed = list.asReversed()
    val reversed   = list.reversed()

    println("Original list: $list")
    println("asReversed:    $asReversed")
    println("reversed:      $reversed")

    list[0] = 10

    println("Original list: $list")
    println("asReversed:    $asReversed")
    println("reversed:      $reversed")

输出

Original list: [0, 1, 2, 3, 4, 5]
asReversed:    [5, 4, 3, 2, 1, 0]
reversed:      [5, 4, 3, 2, 1, 0]
Original list: [10, 1, 2, 3, 4, 5]
asReversed:    [5, 4, 3, 2, 1, 10]
reversed:      [5, 4, 3, 2, 1, 0]

在线尝试!

这篇关于在Kotlin中asReversed()与reversed()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆