【问题标题】:what is the meaning of parentheses with inner and outer classes?内部和外部类的括号是什么意思?
【发布时间】:2021-02-28 22:29:38
【问题描述】:

为什么在 print 语句中没有带外括号的括号,这是什么意思?

    class outer() {
        var name = "mr X"
    
        class nestedclass {
            var description = "Inside the nested class"
            var id = 101
            fun foo() {
                println("id is $id")
    
            }
        }
    }
    
    fun main() {
        println(outer.nestedclass().description)  why there is no () with outer?
        outer.nestedclass().foo()
        var obj = outer.nestedclass()
        obj.foo()
        println(obj.description)
    }

【问题讨论】:

  • 这是不可编译的。你确定 Outer 没有被声明为对象吗?
  • @Tenfour04 编译到这里就OK了(把println()后面的备注注释掉)。
  • 没关系。我被小写的类名和在移动设备上阅读它所迷惑。

标签: kotlin static inner-classes parentheses outer-classes


【解决方案1】:

没有括号,因为它没有创建outer 的实例。

如果nestedclass 是一个内部 类,那么每个实例都将与outer 的一个实例相关联,因此您需要在前者之前构造后者。 (您可以通过添加括号来做到这一点,如 outer().nestedclass()。)

但它只是一个嵌套类——在outer的词法范围内定义,但不与实例相关联。所以outer.nestedclass就是简单的类名,可以直接调用它的构造函数为outer.nestedclass()

所以行:

println(outer.nestedclass().description)

构造outer.nestedclass 的实例,获取其description 属性的值,并将其打印出来。

(如果你懂 Java,这里有两个很大的区别。首先,在 Java 中,内部类是默认的,你需要指定 static 使它们嵌套;但在 Kotlin 中,嵌套类是默认的,还有一个 inner 关键字。其次,Kotlin 没有 Java 的 new 关键字来指示构造函数调用,因此很难发现它们。)

(另外,正如 Tenfour04 所说,conventional 以大写字母(AKA PascalCase)开头的类名。这使得它们更容易与方法名和其他标识符区分开来——这些标识符通常是驼峰式的。这个问题是一个在这种情况下,额外的清晰度会有所帮助。)

【讨论】:

  • 当类不遵循 Pascal-case 命名约定时,特别难以发现构造函数调用。
  • @Tenfour04 确实!我已经评论过很多次了......我们可以设置一个常见问题解答或一些基本的编码约定,关于不必要使用反射的警告,转换和转换之间的区别,以及我们一直在说的其他事情吗?
  • 有时是因为人们只是在使用一种具有不同约定的语言之后才学习这种语言。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-15
  • 1970-01-01
  • 2011-12-20
  • 2019-06-16
相关资源
最近更新 更多