在Kotlin中创建私有内部类的公共实例

时间:2016-12-02 02:39:47

标签: kotlin

为什么Kotlin不允许创建私有内部类的公共实例,而不像Java?

适用于Java:

public class Test {
  public A a = new A();

  private class A {
  }
}

在Kotlin中不起作用(A类必须是public):

class Test {
    var a = A()
//      ^  
// 'public' property exposes its private type 'A'

    private inner class A
}

2 个答案:

答案 0 :(得分:3)

I would assume because there isn't really a case where it seems like the right thing to do. Any code accessing the property a would not have access to its type. You couldn't assign it to a variable. Test.A myVar declaration outside of the Test class would error out. By not allowing it, the code will be forced to be more consistent. A better question would be why would Java allow it? Other languages, such as swift, have the same restriction.

答案 1 :(得分:2)

https://kotlinlang.org/docs/reference/visibility-modifiers.html#classes-and-interfaces

陈述:

  

对Java用户的注意:外部类在Kotlin中看不到其内部类的私有成员。

对于您的用例,您可以使用Nested Classes

private inner classes中,您只能访问外层成员。

我认为kotlin团队以这种方式实现了它,因此可以将private inner classes中的成员范围缩小到只能在inner class内访问。我认为这在Java中是不可能的。