当查看一些 Scala 库的源代码时,例如无形的,我经常发现名为LowPriorityImplicits
.
您能解释一下这个模式吗?解决的问题是什么,该模式是如何解决的?
该模式允许您拥有隐式层次结构,避免编译器产生与歧义相关的错误,并提供一种对它们进行优先级排序的方法。作为示例,请考虑以下内容:
trait MyTypeclass[T] { def foo: String }
object MyTypeclass {
implicit def anyCanBeMyTC[T]: MyTypeclass[T] = new MyTypeclass[T] {
val foo = "any"
}
implicit def specialForString[T](implicit ev: T <:< String): MyTypeclass[T] = new MyTypeclass[T] {
val foo = "string"
}
}
println(implicitly[MyTypeclass[Int]].foo) // Prints "any"
println(implicitly[MyTypeclass[Boolean]].foo) // Prints "any"
println(implicitly[MyTypeclass[String]].foo) // Compilation error
最后一行中出现的错误是:
<console>:25: error: ambiguous implicit values:
both method anyCanBeMyTC in object MyTypeclass of type [T]=> MyTypeclass[T]
and method specialForString in object MyTypeclass of type [T](implicit ev: <: <[T,String])MyTypeclass[T]
match expected type MyTypeclass[String]
println(implicitly[MyTypeclass[String]].foo)
这不会编译,因为隐式解析会发现歧义;在这种情况下,我们定义的有点人为String
当我们可以将其定义为时,使用隐式证据来引发歧义的情况implicit def specialForString: MyTypeclass[String] = ...
并且没有任何歧义。但在某些情况下,您在定义隐式实例时需要依赖其他隐式参数,并使用低优先级模式,您可以按如下方式编写并使其正常工作:
trait MyTypeclass[T] { def foo: String }
trait LowPriorityInstances {
implicit def anyCanBeMyTC[T]: MyTypeclass[T] = new MyTypeclass[T] {
val foo = "any"
}
}
object MyTypeclass extends LowPriorityInstances {
implicit def specialForString[T](implicit ev: T <:< String): MyTypeclass[T] = new MyTypeclass[T] {
val foo = "string"
}
}
println(implicitly[MyTypeclass[Int]].foo) // Prints "any"
println(implicitly[MyTypeclass[Boolean]].foo) // Prints "any"
println(implicitly[MyTypeclass[String]].foo) // Prints "string"
还值得注意的是,这种模式不限于两层,但您可以创建一个特征层次结构,并在其中包含隐式定义,这些定义沿着继承树从更具体到更通用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)