Search code examples
scalanamed-parameters

Can't use a negative number in named parameters in Scala


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


Solution

  • 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)