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 B开发者_运维知识库ar{ }
}
}
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 {})
^
Here's something about what you are doing:
new Foo {} // Anonymous subclass of Object with trait Foo
new Foo () // Foo
new Foo // Foo
When 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
.
精彩评论