Reputation: 413
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
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)
Upvotes: 1