Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 792
Michał Bendowski Avatar asked Oct 07 '11 09:10

Michał Bendowski


2 Answers

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.

like image 141
huynhjl Avatar answered Sep 18 '22 15:09

huynhjl


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(...).

like image 32
Philippe Avatar answered Sep 20 '22 15:09

Philippe