How to determine if a scala module is running as a script

How to determine if a Scala module is open as a script or if it is regularly imported?

This question addresses the same issue as the previous Python question:
how to determine if a python script is imported as a module or run as a script?
but for Scala

+4
source share
4 answers

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

Also, keep in mind that there is a difference between Scala and Python, which makes the question somewhat controversial: in Scala, code expressions cannot be displayed at the top level, unless there is a Scala script, so you will never encounter the ambiguity of writing a Scala script. and then wonder if it is being performed in any other way.

+2
source

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

+1
source
As far as I know,

Scala does not have the Python __main__ equivalent, so this cannot be done in the same way. But I argue that you should not do this anyway - just write tests for your module or write a script that imports the module.

0
source

A dirty hack can be a throw and an exception and get a mark. You can then examine it to try to guess the context. For example, for example:

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

StackTraceElement full stack trace as a StackTraceElement array.

However, writing trace analysis code will be tedious, and I don't see any situation where this might be useful ...

0
source

All Articles