[scalactic] flatten and flatmap on a collection of Or

516 views
Skip to first unread message

Ayoub Benali

unread,
Jul 24, 2015, 4:03:28 PM7/24/15
to scalatest-users
Hello,

I started using Scalactic Or class recently and I was surprised that we cannot flatten (and flatMap) on a collection of Or like the following:

scala> import org.scalactic._
import org.scalactic._

scala> val x: List[Or[Int, String]] = List(Good(1), Bad("foo"), Good(3))
x: List[org.scalactic.Or[Int,String]] = List(Good(1), Bad(foo), Good(3))

scala> x.flatten
<console>:12: error: No implicit view available from org.scalactic.Or[Int,String] => scala.collection.GenTraversableOnce[B].
              x.flatten

The intended goal is to keep only the Good cases and unwrap their values. Is there a specific reason why the library cannot do that by default ? is there an implicit somewhere to allow that ?

The previous example would have worked with a collection of Scala Option because there is an implicit conversion in the companion object  to do the conversion to a GenTraversableOnce.
So adding the following function in scope solved my issue:

scala> import scala.language.implicitConversions
import scala.language.implicitConversions

scala> implicit def orToIterable[A,B](o: Or[A,B]): Iterable[A] = o.toSeq
orToIterable: [A, B](o: org.scalactic.Or[A,B])Iterable[A]

scala> x.flatten
res1: List[Int] = List(1, 3)

If there is no real blocker to have that in the library I could to a pull request.

Best,
Ayoub.

 

Reply all
Reply to author
Forward
0 new messages