lundi 28 décembre 2015

Scala pattern match on classes with a typed paremeter

I'm trying to pattern match on a custom class with a typed parameter:

class Foo[A]

def isMyFoo[A: ClassTag](v: Any) = v match {
    case mine: Foo[A] => "my foo"
    case other: Foo[_] => "not my foo"
    case _ => "not a foo"
}

That will not work; no matter the type of Foo, I will always get "my foo".

The only way I was able to make something like this work, is this:

class Foo[A](implicit t: ClassTag[A]) {
    val tag = t
}

def isMyFoo[A: ClassTag](v: Any) = v match {
    case foo: Foo[_] =>
        if (foo.tag == classTag[A]) "my foo"
        else "not my foo"
    case _ => "not a foo"
}

Is there a more elegant way of doing so? Do I have to keep the ClassTag inside Foo?





Aucun commentaire:

Enregistrer un commentaire