scala - 伴侣对象无法访问类上的私有(private)变量

标签 scala read-eval-print-loop companion-object

来自 Scala REPL 的一个相当奇怪的行为。

尽管以下编译没有问题:

class CompanionObjectTest {
    private val x = 3
}
object CompanionObjectTest {
    def testMethod(y:CompanionObjectTest) = y.x + 3
}

私有(private)变量似乎无法从 REPL 中的伴随对象访问:
scala> class CompanionObjectTest {
     | 
     | private val x = 3;
     | }
defined class CompanionObjectTest

scala> object CompanionObjectTest {
     | 
     | def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
<console>:9: error: value x in class CompanionObjectTest cannot be accessed in CompanionObjectTest
       def testMethod(y:CompanionObjectTest) = y.x + 3
                                                 ^

为什么会这样?

最佳答案

正在发生的事情是 REPL 上的每一“行”实际上都放在不同的包中,因此类和对象不会成为伙伴。您可以通过以下几种方式解决此问题:

制作链类和对象定义:

scala> class CompanionObjectTest {
     |   private val x = 3;
     | }; object CompanionObjectTest {
     |   def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
defined class CompanionObjectTest
defined module CompanionObjectTest

使用粘贴模式:
scala> :paste
// Entering paste mode (ctrl-D to finish)

class CompanionObjectTest {
    private val x = 3
}
object CompanionObjectTest {
    def testMethod(y:CompanionObjectTest) = y.x + 3
}

// Exiting paste mode, now interpreting.

defined class CompanionObjectTest
defined module CompanionObjectTest

将所有内容放入对象中:
scala> object T {
     | class CompanionObjectTest {
     |     private val x = 3
     | }
     | object CompanionObjectTest {
     |     def testMethod(y:CompanionObjectTest) = y.x + 3
     | }
     | }
defined module T

scala> import T._
import T._

关于scala - 伴侣对象无法访问类上的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919965/

相关文章:

java - 伴随对象中的 Kotlin 抽象静态乐趣

scala - 鼠标单击并悬停在 javafx2 上的奇怪行为

Regex JSON 响应 Gatling 压力工具

Scala:抽象类构造函数参数与 Trait val 成员?

python - ipython 和 python 之间的输出差异

swift - 如何重置 Swift REPL?

scala - 在 SPARK REPL 上出现错误(对 A 的引用不明确)并且在 Intellij 和 Scala REPL 中工作正常?

multithreading - 在主线程上等待回调方法

testing - 从 REPL 使用固定装置运行一个 Clojure 测试(不是命名空间中的所有测试)

Scala - 创建扩展密封抽象类的案例对象列表