gpt4 book ai didi

kotlin - 如何访问顶级对象的字段?

转载 作者:行者123 更新时间:2023-12-04 11:52:19 27 4
gpt4 key购买 nike

当我这样做时

val data = object {
val field = 5
}

fun main(){
println(data.field) // throws
}
它抛出 Unresolved reference: field .
但这一切都没问题:
val field = 6

class Data(val field: Int = 7)
val data7 = Data()

fun main(){
val data4 = object {
val field = 4
}
println(field) // ok
println(data4.field) // ok
println(data7.field) // ok
}
我不明白,为什么 Kotlin 不允许我使用顶级对象的属性?我以为 object就像类对象,但匿名(没有类)和 data 应该没有区别和 data7在上面的例子中。但是好像有区别。

最佳答案

这记录在 Language Specification 的“对象文字”部分中。 ,关于对象声明和匿名对象(对象字面量创建的东西)之间的区别。

The main difference between a regular object declaration and an anonymous object is its type. The type of an anonymous object is a special kind of type which is usable (and visible) only in the scope where it is declared. It is similar to a type of a regular object declaration, but, as it cannot be used outside the declaring scope, has some interesting effects.


您的 data这里被认为已经逃脱了“文件的顶级”的声明范围,因为它是公开的。您可以从其他文件的顶级范围访问它。

Note: in this context “escaping current scope” is performed immediately if the corresponding value is declared as a non-private global- or classifier-scope property, as those are parts of an externally accessible interface.


标记它 private会修复它。错误的原因是:

When a value of an anonymous object type escapes current scope:

  • If the type has only one declared supertype, it is implicitly downcasted to this declared supertype;
  • If the type has several declared supertypes, there must be an implicit or explicit cast to any suitable type visible outside the scope, otherwise it is a compile-time error.

这里,父类(super class)型隐式为 Any ,所以 data 的类型是 Any ,显然没有 field在类型 Any .
另一方面, data4没有转义当前范围,因为它是本地的 main函数的语句范围。您无法从其他范围访问它。
另请参阅规范中的优秀示例。

关于kotlin - 如何访问顶级对象的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68690146/

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