如何使用默认参数为case类编写scala提取器?

Jef*_* Wu 4 scala case-class extractor

我有以下case类和一个默认参数,我想知道如何编写一个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])
Run Code Online (Sandbox Code Playgroud)

Dav*_*ook 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)
  }
}
Run Code Online (Sandbox Code Playgroud)

我认为只在案例类中使用通配符是首选,如果这对您有用.

pSeq.map { case Point(x,y,_) => x + y }
Run Code Online (Sandbox Code Playgroud)