scala var args caseclasses

时间:2015-02-26 02:35:36

标签: scala variadic-functions

如何测试构造函数的var arg参数的长度。

我正在定义一个案例类多边形,它接受一系列点,我想确保点的数量至少是5个使用require子句。

case class Point(x: Int, y: Int)
case class Polygon(points: Point*)  {
// require(point >= 3) }

2 个答案:

答案 0 :(得分:6)

这个怎么样?:

 case class Point(x: Int, y: Int)
 case class Polygon(a: Point, b: Point, c: Point, d: Point, e: Point, other: Point*)  {
  def points = Vector(a,b,c,d,e) ++ other
}

然后:

val p1 = Point(1,1)
val p2 = Point(2,1)
val p3 = Point(3,1)
val p4 = Point(4,1)
val p5 = Point(5,1)
val p6 = Point(6,1)
val p7 = Point(7,1)

val polygon5 = Polygon(p1,p2,p3,p4,p5)
println(polygon5.points)
// Vector(Point(1,1), Point(2,1), Point(3,1), Point(4,1), Point(5,1))

val polygon7 = Polygon(p1,p2,p3,p4,p5,p6,p7)
println(polygon7.points)
// Vector(Point(1,1), Point(2,1), Point(3,1), Point(4,1), Point(5,1), Point(6,1), Point(7,1))

Polygon(p1,p2,p3,p4)  // error: not enough arguments for method apply

答案 1 :(得分:4)

通过使该类接受5 Point个参数,然后Point*可变参数通常是您最好的选择(如dhg的答案所示),将此要求转移到编译时间。

如果您想使用require,则非常简单:

case class Polygon(points: Point*)  {
    require(points.length >= 5, "Must have at least 5 points") 
}