Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expose Scala constructor arguments as public members?

Tags:

scala

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! :)

like image 727
user1285925 Avatar asked Mar 25 '12 21:03

user1285925


People also ask

How do you make a Scala constructor private?

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.

How do you provide overloaded constructors in Scala?

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.

Can objects have constructors Scala?

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.

What is constructor in Scala?

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.


2 Answers

Yes, there is:

class Point(val x: Int, val y: Int) 
like image 132
Nicolas Avatar answered Sep 17 '22 22:09

Nicolas


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) 
like image 23
yerlilbilgin Avatar answered Sep 20 '22 22:09

yerlilbilgin