vertexshader
vertexshader

Reputation: 324

Typeclass priority

I have a situation where I have a typeclass with a parameter that must be contravariant. If I have an implicit object defined for both a baseclass and a subclass I get an "ambigious" error, where it doesn't know which implicit object to choose. Is there a way to prioritize the implicit objects? I've seen examples of priorities for implicit conversions, but never for typeclasses. Thanks

trait Coded[-X] { // contravariant
   val x: Int
}

def printCode[O1](p1: O1)(implicit ev: Coded[O1]) =
    println(ev.x)

class Baseclass
class Subclass extends Baseclass

object TEST {
  implicit object code1 extends Coded[Baseclass] { val x = 5 }
  implicit object code2 extends Coded[Subclass ] { val x = 6 }
}

import TEST._

printCode(new Subclass) // error: ambiguous

Upvotes: 3

Views: 87

Answers (1)

som-snytt
som-snytt

Reputation: 39577

You mean?

scala> trait Low { implicit object code1 extends Coded[Baseclass] { val x = 5 } }
defined trait Low

scala> object TEST extends Low { implicit object code2 extends Coded[Subclass ] { val x = 6 } }
defined object TEST

scala> import TEST._
import TEST._

scala> printCode(new Subclass)
6

Upvotes: 4

Related Questions