Try it (partially based on this blog post from Miles Sabin ):
// Your domain trait QueryUnit case class SimpleQuery(query: String, metadata: AnyRef) extends QueryUnit case class ComplexQuery(map: Map[String, Seq[SimpleQuery]]) extends QueryUnit // End of your domain // Something which has type parameter, so we can add QueryUnit, ... trait WrongArg[T] // Create ambiguous implicits for QueryUnit implicit def v0: WrongArg[QueryUnit] = ??? implicit def v2: WrongArg[QueryUnit] = ??? // And valid values for the concrete subclasses implicit val simpleQWrongArg: WrongArg[SimpleQuery] = new WrongArg[SimpleQuery] {} implicit val complexQWrongArg: WrongArg[ComplexQuery] = new WrongArg[ComplexQuery] {} case class API[QU <: QueryUnit]( query: Map[String, Seq[QU]] // Require an evidence that we are getting the correct type )(implicit w: WrongArg[QU]) { } API/*[SimpleQuery]*/(Map("" -> Seq(SimpleQuery("", "")))) API/*[ComplexQuery]*/(Map("" -> Seq(ComplexQuery(Map.empty)))) // Fails to compile because of ambiguous implicits //API(Map("s" -> Seq(SimpleQuery("", "")), "c" -> Seq(ComplexQuery(Map.empty))))
This is not ideal (incorrect names, @implicitNotFound annotation).
The basic idea is that we create ambiguous implications for the base class, but not for subclasses. Due to implicit permission rules, this will compile only for subclasses, but not for the base class.
Purified Version:
@annotation.implicitNotFound("Base QueryUnit is not supported, you cannot mix SimpleQuery and ComplexQuery") trait Handler[T] extends (T => Unit) object API { implicit def baseQueryUnitIsNotSupported0: Handler[QueryUnit] = ??? implicit def baseQueryUnitIsNotSupported1: Handler[QueryUnit] = ??? implicit val simpleQWrongArg: Handler[SimpleQuery] = new Handler[SimpleQuery] { override def apply(s: SimpleQuery): Unit = {} } implicit val complexQWrongArg: Handler[ComplexQuery] = new Handler[ComplexQuery] { override def apply(s: ComplexQuery): Unit = {} } } case class API[QU <: QueryUnit](query: Map[String, Seq[QU]])( implicit handler: Handler[QU]) { // Do something with handler for each input } // Usage import API._ import scala.annotation.implicitNotFound API/*[SimpleQuery]*/(Map("" -> Seq(SimpleQuery("", "")))) API/*[ComplexQuery]*/(Map("" -> Seq(ComplexQuery(Map.empty)))) // Error:(56, 71) Base QueryUnit is not supported, you cannot mix SimpleQuery and ComplexQuery //API(Map("s" -> Seq(SimpleQuery("", "")), "c" -> Seq(ComplexQuery(Map.empty))))
Alternatively with type restrictions and implicitly :
case class API[QU <: QueryUnit: Handler](query: Map[String, Seq[QU]]) { def doSomething: Unit = for {(_, vs) <- query v <- vs} { val handler: Handler[QU] = implicitly[Handler[QU]] handler(v) } }
source share