gpt4 book ai didi

java - Kotlin中如何限制内部类的实例化仅在外部内部?

转载 作者:行者123 更新时间:2023-12-02 03:28:35 25 4
gpt4 key购买 nike

拥有内部类和外部类,我想仅通过外部类的范围来限制内部类的实例化。我怎样才能在 Kotlin 中实现这一目标? Java 以一种非常简单的方式提供了它。但似乎在 Kotlin 中我什至无法从内部类访问私有(private)字段。

Kotlin 拥有什么:

class Outer {
val insideCreatedInner: Inner = Inner()
inner class Inner
}

val insideCreatedInner = Outer().insideCreatedInner // Should be visible and accessible
val outsideCreatedInner = Outer().Inner() // I want to disallow this

Java 如何解决这个问题:

class Outer {
Inner insideCreatedInner = new Inner();
class Inner {
private Inner() {}
}
}

Outer.Inner insideCreatedInner = new Outer().insideCreatedInner;
Outer.Inner outsideCreatedInner = new Outer().new Inner(); // 'Inner()' has private access in 'Outer.Inner'

最佳答案

已编辑:要使 val 字段可见并同时隐藏 Inner 构造函数,使用接口(interface)可能会很有用这是可见的并使实现私有(private):

class Outer {
val insideInner: Inner = InnerImpl()

interface Inner {
// ...
}
private inner class InnerImpl : Inner {
// ...
}
}


val outer = Outer()
val outsideInner = outer.InnerImpl() // Error! Cannot access '<init>': it is private in 'Inner'

关于java - Kotlin中如何限制内部类的实例化仅在外部内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59525497/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com