首页 文章

Kotlin:在使用可变内部时从getter返回不可变集合[duplicate]

提问于
浏览
2

这个问题在这里已有答案:

我有一些字段是集合,可以在包含它的服务中进行变异,而其他一些服务应该能够访问它而不必自己变异 .

在java中它可以像这样实现:

public class Test {

    private final List<Integer> list = new ArrayList<>();

    public List<Integer> getList() {
        return Collections.unmodifiableList(list);
    }
}

在kotlin中,我存储了声明为 MutableList 的字段:

val someCollection: MutableList<Int> = ArrayList()
    get() = unmodifiableList(field)

但是getter显然会返回类型为 MutableList 的对象 .

理想情况下,我希望实现这样的目标:

val someCollection: MutableList<Int> = ArrayList()
        get() = unmodifiableList(field) as List // <-- returns List instead of MutableList

换句话说,可以更改生成的getter的签名以返回另一个接口 . 最有可能的答案是否定的,我想知道为什么?这被认为是一种不好的做法吗?

我看到有可能做这样的事情:

private val _someCollection: MutableList<Int> = ArrayList()
val someCollection: List<Int>
    get() = unmodifiableList(field)

但它似乎比手动创建的getter更糟糕,因为它创建了另一个字段 .

1 回答

  • 1

    不,这在Kotlin目前是不可能的 . 实际上,当前设计强制getter具有与整个属性相同的返回类型 .

    通常,正如您所注意到的,解决方法是使用支持属性 .

    或者,您可以定义具有 List 属性的接口,在类中使用 MutableList 实现它,并使用接口公开该类的实例:

    interface SomeInterface {
        val someList: List<Int>
    }
    
    internal class SomeClass : SomeInterface {
        override val someList: MutableList<Int> = mutableListOf()
    }
    
    fun getSomeInterface(): SomeInterface =
        SomeClass().apply { someList += listOf(1, 2, 3) }
    

    见:a related discussion .

相关问题