Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple issue - "Error: missing argument list for method"

Tags:

scala

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?

like image 382
toni057 Avatar asked Jan 18 '18 12:01

toni057


1 Answers

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

like image 175
airudah Avatar answered Sep 28 '22 16:09

airudah