简体   繁体   English

类和伴随对象如何在Scala中看到私有val?

[英]How can a class and companion object see private vals in Scala?

object Foo {
  private val thing: String = "Yay"
}

case class Foo() {
  println(thing)
}

Is it possible for object Foo's thing to be visible only in class instances of Foo (shared visibility)? 对象Foo的thing是否有可能仅在Foo的类实例(共享可见性)中可见? As shown, compiler complains 如图所示,编译器抱怨

...thing in class is unresolved. ......课堂上的事情尚未解决。

I'd rather not open it up to package-level visibility if it can be avoided. 如果可以避免的话,我宁愿不打开包级别的可见性。

You need to import members of object Foo inside case class: 您需要在案例类中导入object Foo成员:

object Files {

  object Foo {
    private val thing: String = "Yay"
  }

  case class Foo() {
    import Foo._
    println(thing) //ok
  }
}

Using qualified name Foo.thing without import would also work. 使用限定名称Foo.thing而不导入也可以。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM