【发布时间】:2012-09-23 20:06:47
【问题描述】:
我正在开发的程序中有类似于以下代码的内容(仅带有更多参数):
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))
}
}
我想让程序能够接受第一个参数的Position2D对象和第二个参数的两个Doubles,或者第一个参数的两个Doubles和一个@987654325 2nd 参数的 @ 对象,而无需为每个参数组合创建更多 this 语句。我知道可以使用类似的东西:
def this(posObj: Either[Position2D, Array[Double]], velObj: Either[Vector2D, Array[Double]]) = {...}
然后测试一下posObj和velObj是什么类型;但是,我很好奇是否有一种方法可以做到这一点,而不需要 Either 的第 2nd 部分只是一个项目,例如 Array,以便您可以初始化 @987654332 @像下面这样:
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)
【问题讨论】:
标签: scala types parameters constructor