我想在我的代码中添加一个'+:'方法来实现模式匹配,就像提供的List一样
case head::tail => _
所以,我尝试编写这些代码
abstract class Num{
def +: (b:Int):Num
}
case class Entity(a:Int, t:Num) extends Num{
def +: (b:Int):Num = new Entity(b,this)
override def toString:String = "Entity(" + a + "," + t + ")"
}
case object ZERO extends Num{
def +: (b:Int):Num = new Entity(b,this)
override def toString:String = "ZERO"
}
def toIntList(n:Num):List[Int] = n match{
case ZERO => Nil
case (head:Int) +: tail => head :: toIntList(tail)
}
但它们效果不好......
scala> val two = 2 +: ( 1 +: ZERO)
two: Num = Entity(2,Entity(1,ZERO))
scala> toIntList(two)
scala.MatchError: Entity(2,Entity(1,ZERO)) (of class Entity)
at .toIntList(<console>:11)
at .<init>(<console>:14)
at .<clinit>(<console>)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)