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
?