Last active
September 3, 2015 23:57
-
-
Save machisuji/2169cf362eb9a08a5787 to your computer and use it in GitHub Desktop.
optional parameters in Scala that are not a pain to write
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 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