I have the something akin to the following code (only with more parameters) in a program I am developing:
class Particle {
//variables
def this(position: Position2D, velocity: Vector2D) = {
this()
//constructors
}
def this(xPos: Double, yPos: Double, magnitude: Double, angle: Double) = {
this(new Position2D(xPos, yPos), new Vector2D(magnitude, angle))
}
}
And I would like to make it so that the program is able to accept the Position2D object for the first parameter and two Doubles for the second parameter, or two Doubles for the first parameter and a Vector2D object for the 2nd parameter, without creating more this statements for each combination of parameters. I know that it’s possible to use something like:
def this(posObj: Either[Position2D, Array[Double]], velObj: Either[Vector2D, Array[Double]]) = {...}
And then test to see what type posObj and velObj are; however, I was curious if there was a way to do this without requiring the 2nd part of the Either to be just one item such as an Array, so that you could initialize Particle like the following:
val a = new Particle(new Position(3, 6), 30, 5)
val b = new Particle(3, 6, new Vector2D(30, 5))
val c = new Particle(new Position(3, 6), new Vector2D(30, 5))
val d = new Particle(3, 6, 30, 5)
The short answer is no, the constructors are rigid in the sense that the number of parameters (assuming you don’t want them in a Seq) for a method (or constructor in this case) has to be quite specific.
Potentially by enclosing the naked pairs in a Tuple2 and creating a typeclass instance to unpack each this would be possible, but it would be an order of magnitude more complicated than just adding the constructors.