mardi 8 septembre 2015

Generic strongly-typed scala method to retrieve item of a particular type from a collection

Imagine I have this class:

class Example {
    val list = List(new Apple(), new Orange(), Banana());
    def getIfPresent[T <: Fruit] : Option[T] = list.collectFirst { case x : T => x }
}

You use it like this:

val example = new Example();
match example.getIfPresent[Apple] {
    case Some(apple) => apple.someAppleSpecificMethod();
    case None => println("No apple");
}

Now, of course, this doesn't work in the JVM, because of type erasure. getIfPresent just matches on the type Fruit in the collectFirst partial function, instead of the actual type specified in the call.

I have tried to get my head around type tags and class tags, and really have no idea how I would implement the above method. The examples that I see are trying to do very different things. How could I achieve a method that does what I want, either with TypeTags or some other mechanism I'm unaware of?





Aucun commentaire:

Enregistrer un commentaire