Overriding Parameterized Methods in Scala
Note. Apologies for changing this question, I was previously unable to express the exact question I ran into.
Let's say we have an abstract parameterized class abs
,
abstract class abs[T] {
def getA(): T
}
class ABS[Int] extends abs[T] {
override def getA(): Int = 4
}
gives the following weird error:
<console>:28: error: type mismatch;
found : scala.Int(4)
required: Int
override def getA(): Int = 4
^
I want to override a method getA
.
It would also be very helpful to get an explanation or a helpful link.
Maybe you want something like this
abstract class Abs[T] {
def getA: T
def getA(i: T): T
}
class Absz extends Abs[Int]{
override def getA = 4
override def getA(i: Int) = i
}
(new Absz()).getA //> res0: Int = 4
(new Absz()).getA(3) //> res1: Int = 3
With the current base method signature, this is not possible as the generics are being erased.
Take the type tag (I also renamed the method T
to U
to prevent confusion due to shading):
abstract class abs[T] {
def getA[U: TypeTag](): U
}
class ABS[T] extends abs[T] {
override def getA[U]()(implicit tag: TypeTag[U]): U = {
if (tag == typeTag[Int]) new Integer(1)
else if (tag == typeTag[Char]) new Character('1')
else throw new Exception("bad type")
}.asInstanceOf[U]
}
You can do this with Shapeless polymorphic functions: https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0
import shapeless._
object Abs extends Poly0{
implicit def caseInt = at[Int](4)
implicit def caseChar = at[Char]('4')
}
println(Abs.apply[Int])
println(Abs.apply[Char])