Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I syntax check a Scala script without executing the script and generating any class files?

One can write scripts in Scala. So you can put this into Hello.scala

#!/bin/sh
exec scala $0 $@
!#

println("You supplied " + args.length + " arguments!")

and make it executable in Unix by

chmod u+x Hello.scala

Then you can run the script simply by

./Hello.scala

This compiles the script and runs it if there are no syntax errors. However, this does not account for situation when I only want to syntax check without executing the script. I do not want to modify the script (i.e. by removing the #! directive) and I do not want any *.class files to be generated.

How can I syntax check a Scala script?

like image 303
midinastasurazz Avatar asked Mar 05 '11 15:03

midinastasurazz


People also ask

How do I run a Scala command line?

To run Scala from the command-line, download the binaries and unpack the archive. Start the Scala interpreter (aka the “REPL”) by launching scala from where it was unarchived. Start the Scala compiler by launching scalac from where it was unarchived.

How do I compile and run a Scala program?

Press "control o" to save the file and then press enter. Press "control x" to exit the nano editor. To compile the code, type "scalac hello_world. scala" and press enter.


1 Answers

I expect that you actually want a little more than just checking for correct syntax ... presumably what you want to know is that your file would compile correctly if you did actually compile it. That involves type checking as well as syntax checking.

For Scala source files (ie. not scripts) you can specify the -Ystop:refchecks command line argument to cause the compiler to stop before it starts code generation (if you really are only interested in syntactic correctness you could specify -Ystop:parser). If there are errors they will be shown on the console in exactly the same way as if you fully compiled the sources.

For Scala scripts you can also specify the -Ystop:refchecks argument. If you do this, then you will either see compile errors reported on the console or, if there are no errors in the script, you will see the following,

$ scala -Ystop:refchecks Hello.scala 
java.lang.ClassNotFoundException: Main

The ClassNotFoundException indicating that no classfiles have been generated and that your script has not been executed.

like image 130
Miles Sabin Avatar answered Nov 01 '22 07:11

Miles Sabin