Skip to content

Using ScallopOption

Rogach edited this page Apr 28, 2012 · 3 revisions

Since I needed somehow detach the option definition and option retreival, I invented ScallopOption.

Basically, it is a lazy wrapper around the standard scala Option, which batches all operations and evaluates the underlying value only as the last resort.

ScallopOption has several lazy methods defined - map, collect, filter, filterNot, orElse. Also it has almost all other scala.Option methods on it.

So if you want to multiply the value of the option by 3, you can do it like this:

val apples = opt[Int]("apples").map(3*)

Toggling the flag option:

val verbose = opt[Int]("silent").map(!_)

Using for-comprehensions:

val apples = opt[Int]("apples")
val bananas = opt[Int]("bananas")
val weight = for {
  a <- apples 
  if a > 2
  b <- bananas
} yield a * 2 + b * 3

Extracting values

val apples = opt[Int]("apples")
apples() // Int, throws exception if no value
apples.get // Option[Int]

Also, calling isSupplied on the ScallopOption will tell whether this option was present in the argument line, not read from the default value.

Clone this wiki locally