Option method like `collect` that returns Unit?

373 views Asked by At

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.

2

There are 2 answers

2
wheaties On BEST ANSWER

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.

0
Michael Zajac On

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") }