Question

I want to limit a parameter of union type of A and B types, where B is some general type, that will be subtyped. I want to put the objects in this method:

def accept[A](a:A)(implicit ev:FooOrBaish[A]){ /* do something */}

This is, how do I specify the implicits:

case class Foo(i:Int)
trait Baish
case object Bar extends Baish
case class Baz(x:String) extends Baish
class FooOrBaish[A]
object FooOrBaish{
  implicit object FooWit extends FooOrBaish[Foo]
  implicit object BaishWit extends FooOrBaish[Baish]
}

Now, I can put in accept Foo(5), but cannot put there Baz("a") neither Bar, the compiler screams: error: could not find implicit value for parameter ev: FooOrBaish[Baz]. Where can I specify the subtype relation?

Was it helpful?

Solution

Change FooOrBaish's type to be contravariant and it works

class FooOrBaish[-A]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top