1

I have 3 classes:

class AClass 
class Base { val a = "a" }
class BaseOne extends Base { val b = "b" }
class BaseTwo extends Base { val c = "c" }

I want to extend a trait which contains a generic method, I'm not allowed to change the trait

trait Converter {
    def toAClass[T <: Base](e: T): AClass
    def fromAClass[T <: Base](s: AClass): T
}

I want to extend it in several different objects

 object ConverterBaseOne extends Converter { 
 // ERROR
     override def toAClass(e: BaseOne) : AClass = { printf(e.b) } // b is known
     override def fromAlcass(a: AClass) : BaseTwo = {....}
 }

I know there is a way to do it with class parameter: trait Converter[T <: Base] and also saw this post https://stackoverflow.com/a/4627144/980275 I'm asking if there is a solution without changing the trait ??? Thank you

Community
  • 1
  • 1
Tal G.
  • 483
  • 5
  • 15

1 Answers1

5

You are changing the signature of the method, so it is not a legal override, it would break polymorphism. You must either parametrize the Converter trait or use another method name.

You can, however, receive a Base object and cast it, but it is not recommended practice since it may result in an exception at runtime:

object ConverterBaseOne extends Converter { 
  override def toAClass[T <: Base](e: T): AClass = {
    printf(e.asInstanceOf[BaseOne].b)
    // ...
  }
}
instanceof me
  • 38,520
  • 3
  • 31
  • 40
  • Thank you for you quick answer It's a possible solution for toAClass function, it's not the case for the fromAClass one.... you have to do the casting at the running side. – Tal G. Jul 18 '13 at 17:09
  • See the first part of my answer for that. The principle of the `Converter#fromAClass` method is that the caller of the function may specify the wanted return type. So you cannot *override* it and say “You'll only get `BaseTwo`”, that's not how overriding works. – instanceof me Jul 18 '13 at 17:14
  • You right of course. I was hoping that this is something I can do in Scala..... I know that there are Hlists in Shapeless lib that can store different Types so I was hoping for some clever solution here. – Tal G. Jul 18 '13 at 17:18
  • I don't think so without modifying `Converter`. Scala doesn't let you redefine override… – instanceof me Jul 18 '13 at 17:19