user1467422
user1467422

Reputation: 51

scala downcasting with generics

I'm looking for help with the following problem:

case class A(val name: String)
class B(name: String) extends A(name)
class Base[T <: A](param: T)
class SubClass[T <: B](param: T)

object Factory {
  def create[T <: A](param: T) = {
    param.name match {
       case "something" => new Base(param)
       case "something else" => new SubClass(param)
    }
  }
}

The factory doesn't compile because of the mismatch between the param Subclass is expecting (T :< B) and the definition of T in create which isT :< A. Is there a clean solution for this or do I need to downcast on the call to the Subclass constructor? how would the downcast look like?

Just to be clear - when Subclass is contructed with param, param is indeed of T<: B.

Thanks.

Upvotes: 1

Views: 1427

Answers (2)

Luigi Plinge
Luigi Plinge

Reputation: 51109

This compiles and runs OK if you supply the type parameter:

case "something else" => new SubClass[T](param)

Whether it should compile is questionable, as it will give a ClassCastException at runtime if this match occurs and T is not a B.

Cleaner solution is to match on type as Daniel says.

Upvotes: 0

Daniel C. Sobral
Daniel C. Sobral

Reputation: 297195

Why don't you match on param first?

param match {
  case b : B => ...
  case a : A => ...
}

Upvotes: 1

Related Questions