我正在阅读Joshua D. Suereth的Scala In Depth,并且在scala中遇到了关于隐式视图的以下代码:
object test { trait Foo trait Bar object Foo { implicit def fooToBar(f : Foo) = new Bar{ } } }然后定义一个需要Bar作为参数的方法:
def bar(x : Bar) = println("bar")为什么以下工作:
val f = new Foo{} bar(f) // print "bar"但
bar(new Foo{})会导致编译器给出类型不匹配错误:
error: type mismatch; found : java.lang.Object with test.Foo required: test.Bar bar(new Foo {}) ^I was reading Scala In Depth by Joshua D. Suereth, and came across the following code about implicit views in scala:
object test { trait Foo trait Bar object Foo { implicit def fooToBar(f : Foo) = new Bar{ } } }Then define a method that requires a Bar as argument:
def bar(x : Bar) = println("bar")Why the following works:
val f = new Foo{} bar(f) // print "bar"but
bar(new Foo{})would cause the compiler to give type mismatch error:
error: type mismatch; found : java.lang.Object with test.Foo required: test.Bar bar(new Foo {}) ^最满意答案
这是关于你在做什么的事情:
new Foo {} // Anonymous subclass of Object with trait Foo new Foo () // Foo new Foo // Foo当你做bar(new Foo {})这样的事情时,编译器还不知道你在做什么 - 它试图找到一个接受new Foo {}的bar方法,但它还不知道究竟是什么键入new Foo {} ,因为它取决于什么是bar 。
如果声明val f = new Foo{} ,则f的类型变得固定,这有助于编译器找出它应该对bar做什么。
Here's something about what you are doing:
new Foo {} // Anonymous subclass of Object with trait Foo new Foo () // Foo new Foo // FooWhen you do something like bar(new Foo {}), the compiler doesn't know yet what you are doing -- it tries to find a bar method that will accept new Foo {}, but it doesn't know yet exactly what type new Foo {} is, because it depends on what bar is.
If you declare val f = new Foo{}, f's type becomes fixed, which then helps the compiler find out what it should do about bar.
更多推荐
发布评论