【发布时间】:2011-01-17 12:09:13
【问题描述】:
我有一组这样的案例类
abstract class Shape
case class Rectangle(width: Int, height: Int) extends Shape
case class Location(x: Int, y: Int, shape: Shape) extends Shape
case class Circle(radius: Int) extends Shape
case class Group(shape: Shape*) extends Shape
Group 基本上是一个形状数组。我需要定义一个计算尺寸的尺寸方法 对于矩形、圆形和位置,它直接返回一个。但我对集团有困难。
object size extends Shape{
def size(s: Any) : Int = s match {
case Rectangle(x,y) => 1
case Group // how to do it? Also having case Group(shape : Shape*) gives an error
case Circle(r) => 1
case Location(x,y,shape) => 1
}
}
我知道对于 Group,我需要使用 map 并左折叠,但我真的无法为其创建逻辑。 谢谢
【问题讨论】:
标签: scala functional-programming pattern-matching