Erik
Erik

Reputation: 132

In scala, is a unary_ a method or a property?

Since the following are equivalent:

-2 2.unary_-

and since parentheses are optional for methods with no arguments, shouldn't

2.unary_-()

also evaluate to -2 ? Instead, I get:

error: Int does not take parameters

The book I'm working through says that unary_- is a method, though this error seems to suggest it is a property of Int. Is this correct?

Upvotes: 1

Views: 693

Answers (1)

Erik
Erik

Reputation: 132

Proceeding from evan058's advice, I decided to run an experiement:

class Myint1(n:Int) {
    def unary_-() = -n /* method definition has parentheses */
}

class Myint2(n: Int) {
    def unary_- = -n /* no parentheses in definition */
}
val n1 = new Myint1(3)
val n2 = new Myint2(3)

n1.unary_- /* prints -3 */
n2.unary_- /* also gives -3 */

n1.unary_-() /* prints -3 */
n2.unary_-() /* throws error: Int does not take parameters */

So unary_- is a method, not a property. The reason for the behavior is that there is a difference between a method definition with parentheses and without. Note that, expectedly, -n1 and -n2 both result in -3.

Upvotes: 2

Related Questions