1

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.

user1467422
  • 121
  • 8

2 Answers2

1

Why don't you match on param first?

param match {
  case b : B => ...
  case a : A => ...
}
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681
0

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.

Luigi Plinge
  • 50,650
  • 20
  • 113
  • 180