2012-11-24 28 views
4

我有以下案例类与默认参数,我想知道如何编写一个不适用的方法,以便我可以提取前两个参数。如何使用默认参数为case类编写一个scala提取器?

我希望下面的代码是明确的。

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]) 

回答

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 } 
+0

这是行得通!谢谢,我完全忘了我可以使用通配符。 –

+0

这可能是明显的,但你也可以做点情况点(x,y,z)=> x + y //注意z从不使用。我更喜欢这里的通配符。 –

相关问题