Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two ways of starting a scala script, which is preferable?

Tags:

unix

scala

I've learnt from the book Programming in Scala that I could start a scala script by writing:

#!/bin/sh
exec scala "$0" "$@"
!#
println("hello world")

That's ok, but I also tried this style:

#!/usr/bin/env scala
!#
println("hello world")

And found this one also runs correctly.
So I've no idea what's the difference between the two.
And, if both ok, why the book choose the former one to demonstrate, which looks a bit longer?

like image 762
pf_miles Avatar asked Dec 25 '12 12:12

pf_miles


People also ask

How do I save a Scala script?

Another way to execute Scala code is to type it into a text file and save it with a name ending with “. scala”. We can then execute that code by typing “scala filename”. For instance, we can create a file named hello.


1 Answers

They're equivalent. The difference is that the latter runs a shell process to start the Scala interpreter, while the former uses the env program, which is more lightweight than a shell, and obviously doesn't require mixing shell code and Scala in a single file (which might upset your editor and other tools).

like image 196
Fred Foo Avatar answered Oct 15 '22 04:10

Fred Foo