Scala scripts: how to run an uncompiled script?

Besides serious performance issues, Scala is a very powerful language. Therefore, I often use it for scripting tasks inside Bash. Is there a way to simply execute the * .scala file exactly the way I can do with Python files? As far as I know, Python uses bytecode to execute programs like the JVM does. However, there is nothing called pythonc (like scalac or javac) that I need to call to execute this. Therefore, I expect Scala to be able to do the same.

+8
scripting scala
source share
2 answers

I do not use python, but in Scala I can do the most difficult thing:

thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' | scala Welcome to Scala version 2.10.2 (Java HotSpot(TM) Server VM, Java 1.7.0_09). Type in expressions to have them evaluated. Type :help for more information. scala> println(" 3 + 4 = " + (3 + 4)) 3 + 4 = 7 scala> thinkpux:~/proj/mini/forum > 

However, after that I do not have visual feedback in bash, so I have to call clear.

But there is no problem writing a script and executing this:

 thinkpux:~/proj/mini/forum > echo 'println(" 3 + 4 = " + (3 + 4))' > print7.scala thinkpux:~/proj/mini/forum > scala print7.scala 3 + 4 = 7 

Then there are no problems in the shell.

With the closing class, the code will not be executed:

 thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\n' class Foo { println(" 3 + 4 = " + (3 + 4)) } thinkpux:~/proj/mini/forum > scala Foo.scala thinkpux:~/proj/mini/forum > cat Foo.scala class Foo { println(" 3 + 4 = " + (3 + 4)) } 

But with the installation of the class, you can execute the code in it without using the well-known (I hope so) "main" method:

 thinkpux:~/proj/mini/forum > echo -e 'class Foo {\nprintln(" 3 + 4 = " + (3 + 4))\n}\nval foo = new Foo()' > Foo.scala thinkpux:~/proj/mini/forum > cat Foo.scala class Foo { println(" 3 + 4 = " + (3 + 4)) } val foo = new Foo() thinkpux:~/proj/mini/forum > scala Foo.scala 3 + 4 = 7 
+2
source share

scala man page contains some examples of how to run Scala code snippets as if they were a script for both Windows and non-Windows platforms (the examples are copied from the man page below):

Unix

  #!/bin/sh exec scala "$0" "$@" !# Console.println("Hello, world!") argv.toList foreach Console.println 

Window

  ::#! @echo off call scala %0 %* goto :eof ::!# Console.println("Hello, world!") argv.toList foreach Console.println 

To speed up subsequent runs, you can cache the compiled fragment using the -savecompiled option:

  #!/bin/sh exec scala -savecompiled "$0" "$@" !# Console.println("Hello, world!") argv.toList foreach Console.println 

Update : from Scala 2.11 (as indicated in this similar answer ), now you can just do it on Unix:

 #!/usr/bin/env scala println("Hello, world!") println(args.mkString(" ")) 
+17
source share

All Articles