4

How do I determine if a Scala module is opened as script or if it is regularly imported?

This question is about the same issue as previous Python question:
how do I determine whether a python script is imported as module or run as script?
but for Scala

Community
  • 1
  • 1
Harald
  • 240
  • 2
  • 10

4 Answers4

2

If you just need a quick hack for personal use, you can launch the Scala interpreter with a shell script that also sets an environment variable indicating that the interpreter is running.

Also, keep in mind that there's a difference between Scala and Python that makes the question somewhat moot: In Scala, code expressions can't appear at the top level, unless it's a Scala script. So you'll never really have the ambiguity of writing a Scala script and then wondering if it's being executed some other way.

Kipton Barros
  • 21,002
  • 4
  • 67
  • 80
1

All Scala modules are imported regularly, because there is no such thing as opening as a script.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
0

Scala doesn't have the equivalent of Python's __main__ as far as I know so it can't be done in the same way. But I argue you shouldn't be doing this anyway - just write tests for your module or write a script that imports the module.

Derek Wyatt
  • 2,697
  • 15
  • 23
0

A dirty hack could be to throw and exception and get the trace. You can then examine it to try to guess the context. For example a method like:

def stackTrace: Array[StackTraceElement] =
  try {
    1/0 // cause exception
    Array() //Never executed
  } catch {
    case e: Exception => e.getStackTrace
  }

Will return the full stack trace as an array of StackTraceElement.

However, writing the trace analysis code will be tedious and I don't see any situation where it may be worth of it...

paradigmatic
  • 40,153
  • 18
  • 88
  • 147