Reputation: 1003
In Java, I can do this:
class Point{
int x, y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
}
How can I do the same thing in Scala (use the same names in constructor arguments and in class attributes):
class Point(x: Int, y: Int){
//Wrong code
def x = x;
def y = y;
}
Edit
I'm asking this because the code below doesn't work
class Point(x: Int, y: Int) {
def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y)
}
But the following one works:
class Point(px: Int, py: Int) {
def x = px
def y = py
def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y)
}
Upvotes: 0
Views: 2079
Reputation: 20285
In Scala the parameters of the constructor become public attributes of the class if declared as a var
or val
.
scala> class Point(val x: Int, val y: Int){}
defined class Point
scala> val point = new Point(1,1)
point: Point = Point@1bd53074
scala> point.x
res0: Int = 1
scala> point.y
res1: Int = 1
Edit to answer the question in comments "if they were private fields, shouldn't my first code snipped after the edit have worked?"
The constructor class Point(x: Int, y: Int)
generates object-private fields which only allow methods of the Point
class to access the fields x
and y
not other objects of type Point
. that
in the +
method is another object and is not allowed access with this definition. To see this in action define add a method def xy:Int = x + y
which does not generate a compile error.
To have x
and y
accessible to the class use a class-private field which is as follows:
class Point(private val x: Int, private val y: Int) {
def +(that: Point): Point = new Point(this.x + that.x, this.y + that.y)
}
Now they are not accessible outside of the class:
scala> val point = new Point(1,1)
point: Point = Point@43ba9cea
scala> point.x
<console>:10: error: value x in class Point cannot be accessed in Point
point.x
^
scala> point.y
<console>:10: error: value y in class Point cannot be accessed in Point
point.y
You can see this in action by using scalac -Xprint:parser Point.scala
.
Upvotes: 6
Reputation: 88428
You don't need to; the "arguments" in the class declarations are all you need in Scala.
Upvotes: 0