0

I want to add a '+:' method to my code to realise the pattern match like that List offered

case head::tail => _

So, I try to write these codes

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

But they don't work well....

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)
Sughiy
  • 45
  • 5
  • It would be nice if the code is compilable. What is `NUM`, `HEHE` and `hehe`? Thanks – Rado Buransky Mar 03 '14 at 03:01
  • 1
    Duplicates http://stackoverflow.com/q/19426548/1296806 explaining that you need the extractor. There are other explanatory questions as well. – som-snytt Mar 03 '14 at 03:18

0 Answers0