I have a simple class and a companion object with apply methods overloaded:
case class A(val s: String,
val x: Int,
val y: Int,
val z: Int,
val foo: Int => Int,
val l: Option[List[String]])
object A {
def apply(s: String, x: Int, y: Int, z: Int, foo: Int => Int) =
new A(s, x, y, z, foo, None)
def apply(s: String, x: Int, y: Int, z: Int, foo: Int => Int, l: List[String]) =
new A(s, x, y, z, foo, Some(l))
}
Let's also define a function:
def foo(x: Int): Int = x + 1
Using the first constructor works:
scala> val a1 = A("a1", 1, 2, 3, foo)
a1: A = A(a1,1,2,3,$$Lambda$1842/2112068307@598e02f0,None)
However using the second does not:
val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
<console>:24: error: missing argument list for method foo
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `foo _` or `foo(_)` instead of `foo`.
val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
The question(s): What is the reason I need to pass foo _
or foo(_)
instead of just foo as in the a1
example? Also, can I redefine my class to make it possible to just use foo
?
It works fine if foo
is declared as a function val
scala> val foo = (x: Int) => x + 1
foo: Int => Int = <function1>
scala> val a1 = A("a1", 1, 2, 3, foo)
a1: A = A(a1,1,2,3,<function1>,None)
scala> val a2 = A("a1", 1, 2, 3, foo, List("b1", "b2"))
a2: A = A(a1,1,2,3,<function1>,Some(List(b1, b2)))
Why def foo
works fine for a1
I'm not sure, but it might have something to do with case class A
expecting a function instead of a method as these apparently are two different things in scala.
Here is a post that might explain better
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With