[SOLVED] Short form for match on Option

In my code I have quite a lot constructs like that:

def foo(param: Option[Value]): Unit = param match {
  case None: doSomething()
  case Some(value): doSomethingElse(value)
}

Is there any short form for that?

I know there are map and foreach, but both apply only for Some and not for None.

Well, you can use fold although it is weird in this case because the result is a Unit

para.fold(ifEmpty = doSomething())(doSomethingElse)

As I always say, the Scaladoc is your friend.

Thank you!

Scaladoc is indeed your friend, but most of the time it speaks another language :slight_smile: If I don’t know what I am looking for, I cannot reference the Scaladoc, unfortunately.

There’s also

param.map(doSomethingElse).getOrElse(doSomething)

though as with Luis’s suggestion, it’s a bit odd that you end up with an Option[Unit], but oh well.

Your original code seems quite short already to me, and very readable. Even though it’s shortenable using fold or map or something else you devise (perhaps something specific to Unit?), I’m skeptical doing so is a win.

2 Likes