试试这个(部分基于迈尔斯·萨宾 (Miles Sabin) 的这篇博文 https://milessabin.com/blog/2011/06/09/scala-union-types-curry-howard/):
// 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))))
这并不理想(名字错误,没有@implicitNotFound
注解)。
基本思想是我们为基类创建不明确的隐式,但不为子类创建。由于隐式解析规则,这将仅针对子类进行编译,而不针对基类进行编译。
清理后的版本:
@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))))
或者使用类型界限和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)
}
}