Skip to content

Instantly share code, notes, and snippets.

@machisuji
Last active September 3, 2015 23:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save machisuji/2169cf362eb9a08a5787 to your computer and use it in GitHub Desktop.
Save machisuji/2169cf362eb9a08a5787 to your computer and use it in GitHub Desktop.
optional parameters in Scala that are not a pain to write
import scala.language.implicitConversions
case class Optional[+T](value: Option[T])
val omit = Optional(None)
implicit def valueToOptional[T](value: T): Optional[T] = Optional(Some(value))
implicit def optionalToOption[T](opt: Optional[T]): Option[T] = opt.value
def add(a: Int, b: Optional[Int] = omit, c: Optional[Int] = omit): Int =
a + b.getOrElse(0) + c.getOrElse(0)
println(add(42))
println(add(42, 1))
println(add(42, 2, 3))
// as opposed to
def add2(a: Int, b: Option[Int] = None, c: Option[Int] = None): Int =
a + b.getOrElse(0) + c.getOrElse(0)
println(add2(42))
println(add2(42, Some(1)))
println(add2(42, Some(2), Some(3)))
// Yeah, yeah I know. Not the best example as in this case you could just write the default values directly
// into the argument list as shown in the following, but you get the idea. I mean there are cases were
// there simply is no default value.
def add3(a: Int, b: Int = 0, c: Int = 0): Int = a + b + c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment