user435779
user435779

Reputation: 413

Having a companion object seems to maask implicit calls to apply?

Consider this code, which works:

case class Foo(s: String)
Some("bar").map(Foo)

It's technically calling Foo.apply, and that's implied.

But now if I have a companion object:

case class Foo(s: String)
object Foo {
    def apply(): Foo = Foo("default")
}
Some("bar").map(Foo)

Now this doesn't work because it is thinking of Foo.type, as in the object Foo. You have to explicitly say .map(Foo.apply)

Is this justScalaThings, or am I doing something wrong?

(Yes I know in this trivial example I could just default the parameter in the case class declaration, this is just an example. Lots of reasons you might declare a companion object.)

Upvotes: 0

Views: 33

Answers (1)

Markus Appel
Markus Appel

Reputation: 3238

In your first example, there is only Foo.apply fitting .map(Foo).

In the second example you have declared an object called Foo, superceding Foo.apply, which you then try to pass into the map. Because map expects a parameter of type String => A compilation fails.

So as far as I am concerned you have to use .map(Foo.apply).

This for example won't compile either:

case class Foo()

def map[A](f: Unit => A) = ???

map(Foo)

Try it out!

Upvotes: 1

Related Questions