Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala methods ending in _=

I seem to remember Scala treating methods ending in _= specially, so something like this:

object X { var x: Int = 0; def y_=(n : Int) { x = n }}

X.y = 1

should call X.y_=(1). However, in 2.8.0 RC1, I get an error message:

<console>:6: error: value y is not a member of object X
       X.y = 1
         ^

Interestingly, just trying to call the method without parentheses fails as well:

scala> X.y_= 1
<console>:1: error: ';' expected but integer literal found.
       X.y_= 1
             ^

Am I misremembering something which does actually exist or did I just invent it out of whole cloth?

like image 380
Alexey Romanov Avatar asked May 04 '10 13:05

Alexey Romanov


People also ask

How to declare a constant in Scala?

Constant names should be in upper camel case. Similar to Java's static final members, if the member is final, immutable and it belongs to a package object or an object, it may be considered a constant: object Container { val MyConstant = ... } The value: Pi in scala.

What is another name for fields in Scala?

Following is a simple syntax to define a basic class in Scala. This class defines two variables x and y and a method: move, which does not return a value. Class variables are called, fields of the class and methods are called class methods.

What is difference between object and class in Scala?

Difference Between Scala Classes and Objects Definition: A class is defined with the class keyword while an object is defined using the object keyword. Also, whereas a class can take parameters, an object can't take any parameter. Instantiation: To instantiate a regular class, we use the new keyword.

How do you create a class instance in Scala?

The keyword new is used to create an instance of the class. We call the class like a function, as User() , to create an instance of the class.


2 Answers

This is one of those corner cases in Scala. You cannot have a setter without a getter and vice versa.

The following works fine:

scala> object X {
     |   var x: Int = 0
     |   def y = x
     |   def y_=(n: Int) { x = n }
     | }
defined module X

scala> X.y = 45

scala> X.y
res0: Int = 45
like image 98
missingfaktor Avatar answered Sep 29 '22 13:09

missingfaktor


scala> object X { var x: Int = 0; def y_=(n : Int) { x = n }}
defined module X

scala>

scala> X y_= 1

scala> X.x
res1: Int = 1

scala> object X { var x: Int = _; def y = x ; def y_=(n: Int) { x = n } }
defined module X

scala> X.y = 1

scala> X.y
res2: Int = 1

scala>
like image 38
Eastsun Avatar answered Sep 29 '22 13:09

Eastsun