我正在阅读Joshua D. Suereth的Scala In Depth,并且在scala中遇到了关于隐式视图的以下代码:
object test {
trait Foo
trait Bar
object Foo {
implicit def fooToBar(f : Foo) = new Bar{ }
}
}
Run Code Online (Sandbox Code Playgroud)
然后定义一个需要Bar作为参数的方法:
def bar(x : Bar) = println("bar")
Run Code Online (Sandbox Code Playgroud)
为什么以下工作:
val f = new Foo{}
bar(f) // print "bar"
Run Code Online (Sandbox Code Playgroud)
但
bar(new Foo{})
Run Code Online (Sandbox Code Playgroud)
会导致编译器给出类型不匹配错误:
error: type mismatch;
found : java.lang.Object with test.Foo
required: test.Bar
bar(new Foo {})
^
Run Code Online (Sandbox Code Playgroud)