Look at this example:
class Point(x: Double, y: Double){ override def toString = "x: " + x + ", y: " + y def +(sourcePoint: Point) : Point = { return new Point(x + sourcePoint.x, y + sourcePoint.y } }
As you can see I want to define a +
operator method on the Point class. But this won't work because in that method, x
and y
can't be accessed on the sourcePoint
local variable since they are private, so I changed the example into this:
class Point(_x: Double, _y: Double){ var x = _x var y = _y override def toString = "x: " + x + ", y: " + y def +(sourcePoint: Point) : Point = { return new Point(x + sourcePoint.x, y + sourcePoint.y) } }
That obviously worked, however is there an easier way to define these variables instead of going from _x -> x and _y -> y.
Thanks for help and time! :)
In Scala, only a primary constructor is allowed to invoke a superclass constructor. In Scala, we are allowed to make a primary constructor private by using a private keyword in between the class name and the constructor parameter-list.
A scala class can contain zero or more auxiliary constructors. The auxiliary constructor in Scala is used for constructor overloading and defined as a method using this name. The auxiliary constructor must call either previously defined auxiliary constructors or primary constructors in the first line of its body.
Constructors in Scala describe special methods used to initialize objects. When an object of that class needs to be created, it calls the constructor of the class. It can be used to set initial or default values for object attributes.
Scala constructor is used for creating an instance of a class. There are two types of constructor in Scala – Primary and Auxiliary. Not a special method, a constructor is different in Scala than in Java constructors. The class' body is the primary constructor and the parameter list follows the class name.
Yes, there is:
class Point(val x: Int, val y: Int)
using val
is valid but then the parameter becomes final (constant). If you want to be able to reassign the value you should use var
instead. So
class Point(var x: Int, var y: Int)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With