Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
Scala OptionParser that doesn't worry about descriptions (we write man pages for that)
def main(args: Array[String]) {
// Required positional arguments by key in options
val required = List('arg1, 'arg2)
// Options with value
val optional = Map("--option|-o" -> 'option, "-t|--test" -> 'test)
// Flags
val flags = Map("--flag1|-f" -> 'flag1, "--flag2" -> 'flag2)
// Default options that are passed in
var defaultOptions = Map[Symbol, String]( 'test -> "hello world!")
// Parse options based on the command line args
val options = parseOptions(args.toList, required, optional, flags, defaultOptions)
implicit class OptionMapImprovements(val m: Map[String, Symbol]) {
def match_key(opt: String): String = {
def match_get(opt: String): Option[Symbol] = {
def match_apply(opt: String): Symbol = {
type OptionMap = Map[Symbol, String]
type OptionMapBuilder = Map[String, Symbol]
def parseOptions(args: List[String],
required: List[Symbol],
optional: OptionMapBuilder,
flags: OptionMapBuilder,
options: OptionMap = Map[Symbol, String](),
strict: Boolean = false
): OptionMap = {
args match {
// Empty list
case Nil => options
// Options with values
case key :: value :: tail if optional.match_get(key) != None =>
parseOptions(tail, required, optional, flags, options ++ Map(optional.match_apply(key) -> value))
// Flags
case key :: tail if flags.match_get(key) != None =>
parseOptions(tail, required, optional, flags, options ++ Map(flags.match_apply(key) -> "true"))
// Positional arguments
case value :: tail if required != Nil =>
parseOptions(tail, required.tail, optional, flags, options ++ Map(required.head -> value))
// Generate symbols out of remaining arguments
case value :: tail if !strict => parseOptions(tail, required, optional, flags, options ++ Map(Symbol(value) -> value))
case _ if strict =>
printf("Unknown argument(s): %s\n", args.mkString(", "))

Based on this:

  • Only fail if strict is set
  • Make defaultOptions optional. Should do the same with every other argument.
  • If strict is not set, create symbols out of all extra cmd line arguments.
  • Allow use of flags and options with values.
  • Allow using short and long options. e.g. -t|--test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.