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.

4

2 回答 2

3

collect如果你的函数返回 a就使用Unit它,如果没有,不要坚持它。

myOpt collect { 
  case x: Foo =>
}

如果您丢弃退货,则没有伤害,没有家禽。

于 2014-11-13T15:42:17.337 回答
1

没有这样Option的方法,让scala直接丢弃返回值就好了collect,但是如果你真的想要一个不同的方法名,你可以使用隐式转换来丰富Option

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

(我不知道你真正称这个函数是什么。)

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") }
于 2014-11-13T15:52:26.140 回答