2

I've been coding on Scala for 2 years and I use a lot of Option's in my code. I feel it is very clear, easy to understand and can easily be treated. This is a normal approach:

val optString = Some("hello")

optString match {
    case Some(str) => //do something here!
    case None => //do something here
}

I thought that this was the best way to treat Scala Options, but I want to ask if there's a better way to do so?

Sohum Sachdev
  • 1,397
  • 1
  • 11
  • 23

1 Answers1

4

It really depends on the use case. A general pattern I take when I have an option and I need either to apply an operation to Some or None which yields the same value is to use Option.fold:

val opt = Some(1)
val res: Int = opt.fold(0)(existing => existing + 1)

If you don't like fold, map and getOrElse will do that same trick in reverse:

val res: Int = opt.map(_ + 1).getOrElse(0)

If I want to continue inside the Option container, map does the trick.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
  • That's true, but doesn't this come out as a little unintuitive? – Sohum Sachdev Aug 28 '17 at 11:46
  • @SohumSachdev You mean `fold`? I find it very intuitive, but I think that's opinion based in general. I've added another pattern using `map + getOrElse`, maybe you'll find that more intuitive. – Yuval Itzchakov Aug 28 '17 at 11:48
  • Just note that the `map + getOrElse` is *not* equivalent: `opt.map(_ + 1).getOrElse("foo")` compiles and runs fine while `opt.fold("foo")(_ + 1)` gives `error: type mismatch; found : Int(1); required: String` as you would expect – bijancn Mar 14 '18 at 11:43
  • @bojancn To type inference it might be a little more constrained, yes. But is that a useful example at all? What would you use as the inferred type? `Any`? – Yuval Itzchakov Mar 14 '18 at 15:48