Created
October 19, 2014 10:28
-
-
Save wookietreiber/173a135290aaf428d244 to your computer and use it in GitHub Desktop.
last option for scala scripts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import annotation.tailrec | |
def optLast[A](opts: String*)(convert: String => Option[A])(implicit args: List[String]): Option[A] = { | |
val longOpts = opts filter { _ startsWith "--" } | |
val longOptsRE = longOpts.mkString("^(","|",")=(.+)").r | |
@tailrec def optLastInternal(current: Option[A], args: List[String]): Option[A] = args match { | |
case Nil => | |
current | |
case opt :: arg :: tail if opts contains opt => | |
optLastInternal(convert(arg), tail) | |
case longOptsRE(_, arg) :: tail => | |
optLastInternal(convert(arg), tail) | |
case _ :: tail => | |
optLastInternal(current, tail) | |
} | |
optLastInternal(None, args) | |
} | |
// example | |
implicit val arguments = args.toList | |
val projectArg: Option[String] = optLast("-p", "--project") { | |
arg => Some(arg) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment