4

我有以下带有默认参数的案例类,我想知道如何编写一个 unapply 方法,以便我可以提取前两个参数。

我希望下面的代码很清楚。

case class Point(x: Double, y: Double, _key: Option[String] = None) {
  def key: String = _key.getOrElse("")
}

object Point {
  def unapply(p: Point) = (p.x, p.y)
}

// pSeq is Seq[Point]
pSeq.map { case Point(x,y) => x + y } // This causes a compiler error:
                                      // wrong number of arguments for <none>: 
                                      // (x: Double, y: Double, _key: Option[String])
4

1 回答 1

6

我不确定这是否是您正在寻找的,但它会为您提供您描述的 API。

sealed abstract class Point(x: Double, y: Double)
case class PointKey(x: Double, y: Double, _key: String) extends Point(x,y)
case class PointNoKey(x: Double, y: Double) extends Point(x,y)
object Point {
  def apply(x: Double, y: Double) = PointNoKey(x,y)
  def apply(x: Double, y: Double, _key: String) = PointKey(x,y,_key)
  def unapply(p: Point): Option[(Double,Double)] = p  match {
    case PointNoKey(x,y) => Some(x,y)
    case PointKey(x,y,_) => Some(x,y)
  }
}

我认为如果对您有用,最好在案例类中使用通配符。

pSeq.map { case Point(x,y,_) => x + y }
于 2012-11-24T02:38:14.597 回答