0

Hi I'm trying to run my code, I double checked everything. It supposed to work, I mean IDE doesn't give any warnings. But when it is compiling I am getting this error

Error:(20, 40) _ must follow method; cannot follow () => Boolean
        properties += new Property(propName, formula _)

here is code part which causes this error

def property(propName: String)(formula: () =>  Boolean)  {
        properties += new Property(propName, formula _)
    }

this is the Property class

class Property(val name: String, val func: () => Boolean)

what's the thing that I am missing here?

Erdi İzgi
  • 1,262
  • 2
  • 15
  • 33

2 Answers2

4

You don't need the underscore here. The underscore would only be needed when you want to convert a method to a function via eta-expansion. This isn't necessary here because formula is already a function of the type () => Boolean, which is what the Property class is looking for.

def property(propName: String)(formula: () =>  Boolean)  {
    properties += new Property(propName, formula)
}
Michael Zajac
  • 55,144
  • 7
  • 113
  • 138
  • So that's why it doesn't give errors when I make it `def property(propName: String)(formula: => Boolean)` ? – Erdi İzgi Nov 07 '16 at 23:13
  • `=> Boolean` is not completely the same as `Function1[Boolean]`. You will notice if you leave off the `_` that you *will* get an error. This is [yet another](http://stackoverflow.com/a/8001065/1374461) usage of `_` in Scala. – Jasper-M Nov 09 '16 at 16:22
3

Just like the warning says. _ must follow a method to turn it into a function. formula already is a function. So you can just pass it like this:

properties += new Property(propName, formula)
Jasper-M
  • 14,966
  • 2
  • 26
  • 37