How to use members with default (package) or private access level in REPL?

主宰稳场 提交于 2019-12-01 02:52:53

问题


I was trying to add some interactivity to my test/debug cycle, so I tried playing around with my classes from the Scala REPL. This works great but has the disadvantage that I cannot access package- and private-level members, that can be tested from a unit test (if the test is in the same package).

Can I "set" the package "context" of the Scala REPL?

I guess I could use reflection to access the members, but that's so much typing it would defeat the purpose of using the REPL in the first place.


回答1:


I assume the class you are testing are written in Java as you have to go out of your way to create package only member in Scala.

In short, it's not possible. Each line in the REPL is wrapped into it's own package, so it won't be allowed to access another package-only member from any other package. Even though there is an undocumented system property to change the default package name prefix used for wrapping, the package name is still generated automatically by incrementing a number:

$ scala -Xprint:parser -Dscala.repl.naming.line=foo.line
scala> val x = 1
[[syntax trees at end of parser]]// Scala source: <console>
package foo.line1 {
  object $read extends scala.ScalaObject {
    // snip ...
    object $iw extends scala.ScalaObject {
      // snip ...
      object $iw extends scala.ScalaObject {
        // snip ...
        val x = 1
      }
    }
  }

Assuming this is something you do often, what you could do is create a file that makes the reflection easy to use and then load it into the REPL using :load command.




回答2:


Do you mean that you cannot access members defined in the package object? You can import these members using

import mypackage._

or simply access them using the prefixed form mypackage.mymember(...).



来源:https://stackoverflow.com/questions/7685645/how-to-use-members-with-default-package-or-private-access-level-in-repl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!