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

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

本文介绍了在Kotlin中创建私有内部类的公共实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Why Kotlin doesn't allow creation of public instances of private inner classes unlike Java?

在Java中工作:

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

  private class A {
  }
}

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

Doesn't work in Kotlin (A class has to be public):

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

    private inner class A
}

我会假定

推荐答案

因为实际上并没有出现看起来正确的事情.任何访问属性a的代码都无法访问其类型.您无法将其分配给变量.在Test类之外的Test.A myVar声明将出错.通过不允许它,代码将被迫变得更加一致.一个更好的问题是Java为什么会允许它?其他语言,例如swift,也有相同的限制.

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.

这篇关于在Kotlin中创建私有内部类的公共实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:33