What's the best way to parse command-line parameters in Scala? I personally prefer something lightweight that does not require external jar.
Related:
What's the best way to parse command-line parameters in Scala? I personally prefer something lightweight that does not require external jar.
Related:
Here is mine 1-liner
It drops 3 mandatory arguments and gives out the options. Integers are specified like notorious
-Xmx<size>
java option, jointly with the prefix. You can parse binaries and integers as simple asNo need to import anything.
For most cases you do not need an external parser. Scala's pattern matching allows consuming args in a functional style. For example:
will print, for example:
This version only takes one infile. Easy to improve on (by using a List).
Note also that this approach allows for concatenation of multiple command line arguments - even more than two!
There's also JCommander (disclaimer: I created it):
I liked the slide() approach of joslinm just not the mutable vars ;) So here's an immutable way to that approach:
I just created my simple enumeration
I understand that solution has two major flaws that may distract you: It eliminates the freedom (i.e. the dependence on other libraries, that you value so much) and redundancy (the DRY principle, you do type the option name only once, as Scala program variable and eliminate it second time typed as command line text).
I have never liked ruby like option parsers. Most developers that used them never write a proper man page for their scripts and end up with pages long options not organized in a proper way because of their parser.
I have always preferred Perl's way of doing things with Perl's Getopt::Long.
I am working on a scala implementation of it. The early API looks something like this:
So calling
script
like this:Would print:
And return:
The project is hosted in github scala-getoptions.