0

I want to get first argument for main method that is optional, something like this:

val all = args(0) == "all"

However, this would fail with exception if no argument is provided.

Is there any one-liner simple method to set all to false when args[0] is missing; and not doing the common if-no-args-set-false-else... thingy?

dk14
  • 22,206
  • 4
  • 51
  • 88
igr
  • 10,199
  • 13
  • 65
  • 111

4 Answers4

14

In general case you can use lifting:

 args.lift(0).map(_ == "all").getOrElse(false)

Or even (thanks to @enzyme):

 args.lift(0).contains("all")
dk14
  • 22,206
  • 4
  • 51
  • 88
1

You can use headOption and fold (on Option):

val all = args.headOption.fold(false)(_ == "all")

Of course, as @mohit pointed out, map followed by getOrElse will work as well.

If you really need indexed access, you could pimp a get method on any Seq:

implicit class RichIndexedSeq[V, T <% Seq[V]](seq: T) {
  def get(i: Int): Option[V] =
    if (i < 0 || i >= seq.length) None
    else Some(seq(i))
}

However, if this is really about arguments, you'll be probably better off, handling arguments in a fold:

case class MyArgs(n: Int = 1, debug: Boolean = false,
    file: Option[String] = None)

val myArgs = args.foldLeft(MyArgs()) {
  case (args, "-debug") =>
    args.copy(debug = true)
  case (args, str) if str.startsWith("-n") =>
    args.copy(n = ???) // parse string
  case (args, str) if str.startsWith("-f") =>
    args.copy(file = Some(???) // parse string
  case _ => 
    sys.error("Unknown arg")
}

if (myArgs.file.isEmpty)
  sys.error("Need file")
gzm0
  • 14,752
  • 1
  • 36
  • 64
1

You can use foldLeft with initial false value:

val all = (false /: args)(_ | _ == "all")

But be careful, One Liners can be difficult to read.

user5102379
  • 1,492
  • 9
  • 9
0

Something like this will work assuming args(0) returns Some or None:

val all = args(0).map(_ == "all").getOrElse(false)

mohit
  • 4,968
  • 1
  • 22
  • 39