Kotlin:通过强制转换(不可变)列表,这合法吗? [英] Kotlin: Modifying (immutable) List through cast, is it legitimate?

查看:100
本文介绍了Kotlin:通过强制转换(不可变)列表,这合法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道Kotlin中的列表是不可变的,即您不能按以下方式进行添加和删除.

As we know the List in Kotlin is immutable i.e. you can't do add and remove as below.

class TempClass {
    var myList: List<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        myList!!.add(10)
        myList!!.remove(10)
    }
}

但是,如果我们按如下所示将其强制转换为ArrayList,则添加和删除均有效.

But if we cast it to ArrayList as below, the add and remove works.

class TempClass {
    var myList: List<Int>? = null
    fun doSomething() {
        myList = ArrayList<Int>()
        (myList!! as ArrayList).add(10)
        (myList!! as ArrayList).remove(10)
    }
}

我只是认为这很奇怪,因为myList实际上是一个List,应该是不可变的.并对其进行投射,允许对其进行更改.

I just thought this is odd, as myList is really a List, which is suppose to be immutable. And casting it, allow it to be altered.

上面所做的(广播到Array并修改内容)是合法的,还是需要改进语言以禁止这样做?

Is what done above (casting to Array and modify the content) legitimate, or the language need to improve to disallow that?

推荐答案

有几种不同类型的不变性:

There are a few different types of immutability:

在单独的SO答案中提到一个此处.

One is mentioned from a separate SO answer here.

只读-您不应该更改它(科特林的列表),但可以更改某些内容(广播到Mutable或从Java更改).

Readonly - you are NOT supposed to change it (Kotlin's List) but something may (cast to Mutable, or change from Java).

List只是一个没有变异方法的接口,但是如果将其强制转换为MutableList,则可以更改该实例.

List is just an interface that does not have mutating methods, but you can change the instance if you cast it to MutableList.

然后有人继续评论说Kotlin选择为只读以便直接使用Java集合,因此使用Java集合不会产生任何开销或转换.

Someone then goes on to comment that Kotlin chose to be readonly in order to use Java collections directly, so there is no overhead or conversion in using Java collections.

科林列表是只读的,不是一成不变的.其他调用者(例如Java)可以更改列表. Kotlin呼叫者可能会投射列表并进行更改.没有一成不变的保护.

Kotlin List is readonly, not immutable. Other callers (Java for example) may change the list. Kotlin callers might cast the list and change it. There is no immutable protection.

原始来源: Kotlin和不可变集合?

这篇关于Kotlin:通过强制转换(不可变)列表,这合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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