Kamal Banga
Kamal Banga

Reputation: 107

Overriding parameterized methods in Scala

Note: I apologise for altering this question, previously I wan't able to express the exact issue I am facing.

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 incomprehensible error:

<console>:28: error: type mismatch;
 found   : scala.Int(4)
 required: Int
       override def getA(): Int = 4
                              ^

I want to override the method getA.

Also an explanation or some helpful link would be really appreciated.

Upvotes: 1

Views: 1113

Answers (3)

mohit
mohit

Reputation: 4999

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

Upvotes: 1

user1804599
user1804599

Reputation:

With the current base method signature this is impossible since generics are erased.

Take a type tag (I also renamed the method's T to U to prevent confusion because of shadowing):

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]
}

Upvotes: 1

Eugene Zhulenev
Eugene Zhulenev

Reputation: 9734

You can do it 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])

Upvotes: 0

Related Questions