How can we pass arguments to scala script like how we pass arguments to a shell script.
2 Answers
Declare your script with bash command on top like this
Test.scala
#!/bin/sh
exec scala "$0" "$@"
!#
object Test {
def main(args: Array[String]): Unit = {
println(s"args: ${args.mkString("[", ", ", "]")}")
}
}
It works
[Desktop] ./Test.scala "scala is awesome" "java8 has lambdas"
args: [scala is awesome, java8 has lambdas]
More info regarding $0 and $@
0 Expands to the name of the shell or shell script.
This is set at shell initialization. If bash is
invoked with a file of commands, $0 is set to
the name of that file. If bash is started with
the -c option, then $0 is set to the first argument
after the string to be executed, if one is present.
Otherwise, it is set to the file name used to invoke
bash, as given by argument zero.
@ Expands to the positional parameters, starting from
one. When the expansion occurs within double quotes, each
parameter expands to a separate word. That is, "$@" is
equivalent to "$1", "$2" ... If the double-quoted
expansion occurs within a word, the expansion of the first
parameter is joined with the beginning part of the original
word, and the expansion of the last parameter is joined
with the last part of the original word. When there are no
positional parameters, "$@" and $@ expand to nothing
(i.e., they are removed).
for more info visit: Command line args for Scala scripts
4 Comments
Kullayappa M
Thanks for swift reply, for some reason I'm not able to get. never mind. Currently I'm working on scala shell means scala>:load test.scala so how to pass parameters here? sorry I'm new to scala
Nagarjuna Pamu
@KPM scala scripts are run on command line like bash scripts. You must not load in into repl. Check in the answer, I have used
./Test.scala on the command line. No need to load it into replKullayappa M
I'm getting exec. scala. not found. could you please hint me ?
Nagarjuna Pamu
@KPM Install scala first from here scala-lang.org/download