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?

4 Answers 4

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")
Sign up to request clarification or add additional context in comments.

1 Comment

args.lift(0).contains("all")
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")

Comments

1

You can use foldLeft with initial false value:

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

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

Comments

0

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

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

2 Comments

Last time I checked, List does not have a get method either.
args.lift(0).map(...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.