Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 980
gaijinco Avatar asked Nov 06 '14 21:11

gaijinco


People also ask

Can char data type have negative numbers?

Char is an unsigned type and cannot represent a negative value. In any case, you should not use Char to hold numeric values.

Can int accept negative values?

An int is signed by default, meaning it can represent both positive and negative values.

Can I be negative in a for loop?

As the name suggests, the positiveornegativenumber variable can contain either a positive or negative number. As a result, if said variable is positive, the for loop works. If it is negative, the loop exits immediately because i is already larger than negativeorpositivenumber.

Does Isdigit work for negatives?

isdigit() function, which returns True when the given string is a positive integer. However, it returns False when the string is a float number or a negative number. That's all about determining whether a given string is numeric in Python.


1 Answers

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)
like image 149
DNA Avatar answered Sep 30 '22 06:09

DNA