1

Is there a method on the Option class that works like collect (it takes a partial function), but has a return type of Unit?

That is: map is to collect as foreach is to ?.

Sorry, I'm new to Scala--I've looked over the Option docs and did a little research, but didn't find anything relevant.

I know I can just use match, I was just wondering if there was a simpler solution.

Jacob Brown
  • 7,221
  • 4
  • 30
  • 50

2 Answers2

3

Just use collect if your function returns a Unit and if it doesn't, don't hold on to it.

myOpt collect { 
  case x: Foo =>
}

no harm, no fowl if you discard the return.

wheaties
  • 35,646
  • 15
  • 94
  • 131
  • okay, thanks, that seems fair. Quick question: in this case, why does `Option` need to have a `foreach`, when there is `map` available? – Jacob Brown Nov 13 '14 at 15:50
  • @kardeiz `foreach` makes it clear that you're executing a side-effecting function, where `map` does not. – Michael Zajac Nov 13 '14 at 15:53
1

There is no such method for Option, and it's fine to let scala just discard the return value from collect, but if you really want a different method name, you can use an implicit conversion to enrich Option.

implicit class OptionExt[A](opt: Option[A]) {
    def forCollect(pf: PartialFunction[A, Unit]): Unit = opt.collect(pf)
}

(I have no idea what you'd really call this function.)

scala> Option[Any](1).forCollect { case i: Int => println("I'm an Int") }
I'm an Int

scala> Option[Any]("1").forCollect { case i: Int => println("I'm an Int") }

scala> Option[Any](None).forCollect { case i: Int => println("I'm an Int") }
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138