15

Is there any way to get a list of bound variables in scala?

Mark Garcia
  • 17,424
  • 4
  • 58
  • 94
Reyan
  • 584
  • 1
  • 5
  • 16
  • 2
    What are the *bound* variables? – om-nom-nom Jan 08 '13 at 19:25
  • I am using a scala interpreter, and I would like to get a list of all the global variables that are currently defined – Reyan Jan 08 '13 at 19:28
  • I'm wondering if there's something similar to this solution for Python: http://stackoverflow.com/questions/3784353/python-print-names-and-values-of-all-bound-variables – Reyan Jan 08 '13 at 19:32
  • Somethiing like locals() in python? Sounds good. Good question. – santiagobasulto Jan 08 '13 at 19:48
  • _bound_ variables are those with bindings! Meaning those for which a value has been established (as opposed to the countable infinity of names in any given scope that have not been given a value...). – Randall Schulz Jan 08 '13 at 22:06

3 Answers3

24

In :power mode in 2.9, 2.10, and 2.11 you can intp.visibleTermNames.sorted.foreach(println) to get everything, or intp.definedTerms.foreach(println) for just the things you've created.

In 2.10, $intp is always visible (power mode or no), so $intp.definedTerms.foreach(println) will print a list in non-power mode.

Try intp.+tab in power mode to list all the methods available. (Symbols starting with $ don't have tab-completion enabled.)

Alexander Oh
  • 24,223
  • 14
  • 73
  • 76
Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
6

In Scala 2.10 REPL, it is possible to access instance of IMain associated with the REPL. It is available as $intp. It seems that it is possible to deeply inspect REPL state with this.

For example, $intp.unqualifiedIds may be helpful to you.

ghik
  • 10,706
  • 1
  • 37
  • 50
4

In the REPL you can use the :dump command to print the internal state of the REPL. One of the first lines should be something like:

Names: $ires0 $ires1 $ires2 $ires3 $ires4 $ires5 $ires6 $ires7 $r x z

These are all variables, classes and singletons you defined in this session.

I don't know of a way to only show the variables.

edit:

before the :dump command is available you have to enter the power mode with :power

drexin
  • 24,225
  • 4
  • 67
  • 81
  • Thanks for the suggestion. That might work, except that I am unfortunately using a different interpreter which doesn't handle the same special commands – Reyan Jan 08 '13 at 20:43