1 year ago

#371783

test-img

micsza

Parametrized pattern matching issue

Suppose I have the following type hierarchy

sealed trait Animal

case class Dog(name: String) extends Animal
case class Cat(age: Int) extends Animal 

Then if given as: List[Animal] I want to drop all the first encounters of cats then I can do

as.dropWhile {
    case d: Dog => false
    case _ => true
}

But when trying to parametrized this kind of search like this:

def findFirst[A <: Animal](as: List[Animal]): List[Animal] = {
    as.dropWhile {
        case a: A =>  false 
        case _ => true
    }
}

the compiler seems to erase the A type.

Is there any workaround for this?

scala

pattern-matching

type-erasure

0 Answers

Your Answer

Accepted video resources