I tried writing a function with a generic return type but it doesn't work unless I cast the return type. Please see the function getSomething()
below I expected it to work without the casting. What might I be doing wrong here?
trait Sup
class Sub extends Sup {
def getString = "I am Sub"
}
class Sub2 extends Sup {
def getInt = 100
}
def getSomething[A <: Sup](str: String) : A = {
str match {
case "sub" => getSub.asInstanceOf[A]
case "sub2" => getSub2.asInstanceOf[A]
}
}
def getSub(): Sub = {
new Sub
}
def getSub2() : Sub2 = {
new Sub2
}
val x = getSomething[Sub]("sub").getString
val y = getSomething[Sub2]("sub2").getInt
Sub
andSub2
are case classes wherestr
andnumber
are case class parameters? Is there a way then to solve the problem with type classes? – Asmodeus