7

I'm using Scala 2.11.2.

If I have this Fraction class:

case class Fraction(numerator: Int, denominator: Int) {}

Then this gives an error:

val f = new Fraction(numerator=-1, denominator=2)

But this is not:

val f = new Fraction(-1, denominator=2)

The error message is:

Multiple markers at this line
- not found: value 
 numerator
- not found: value 
 numerator

I tried to use negative numbers in other snippets with the same result, but the documentation doesn't mentions that this is not possible.

Am I doing something wrong?

Thanks

gaijinco
  • 2,146
  • 4
  • 17
  • 16

1 Answers1

13

You need a space between the = and the -, or you can wrap the -1 in parentheses, otherwise the compiler gets confused. This is because =- is a valid method name, so the compiler cannot tell whether you are assigning a value to a named parameter, or making a method call.

so this gives an error:

val f = Fraction(numerator=-1, denominator=2)

but this is OK:

val f = Fraction(numerator = -1, denominator = 2)

and so is this:

val f = Fraction(numerator=(-1), denominator=2)
DNA
  • 42,007
  • 12
  • 107
  • 146
  • 1
    Also `new` keyword is not required. Its a case class. – tuxdna Nov 06 '14 at 22:10
  • `numerator= -1` should be enough – om-nom-nom Nov 06 '14 at 22:51
  • Yes, that's fine too - just need to separate the `=` and `-` – DNA Nov 06 '14 at 23:04
  • `-Xprint:parser` helps diagnose it. Also, not sure this isn't a parser bug or room for improvement. SIP-1 just says it has the form `x = expr`, "same syntax as variable assignments." Probably asking too much to parse twice; the way it must try both named arg and assignment. – som-snytt Nov 07 '14 at 10:49