假设我有两组类,第一组继承自Foo,第二组继承自Bar.
class Foo
class Baz extends Foo
class Bar
class Qux extends Bar
Run Code Online (Sandbox Code Playgroud)
我想创建一个通用的隐式转换函数,将任何Foo转换为Bar,因为范围内有隐式转换器类型.
trait Converter[A <: Foo, B <: Bar] {
def convert(a : A) : B
}
implicit object BazToQuxConverter extends Converter[Baz, Qux] {
def convert(a : Baz) : Qux = new Qux
}
implicit def FooToBar[A <: Foo, B <: Bar](a : A)(implicit converter : Converter[A, B]) : B = converter.convert(a)
Run Code Online (Sandbox Code Playgroud)
不幸的是,这似乎不像我期望的那样有效.当我将以下行插入REPL时:
val a : Baz = new Baz
val b : Qux = a
Run Code Online (Sandbox Code Playgroud)
...我收到以下错误:
<console>:17: …Run Code Online (Sandbox Code Playgroud)