markmarch
markmarch

Reputation: 214

Implicit views in companion object

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 {})
              ^

Upvotes: 4

Views: 506

Answers (1)

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297165

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.

Upvotes: 6

Related Questions