scalatypesextending-classes

Scala conflict of types when extending a class


I have defined an abstract base class like following:

abstract class Base() {
    val somevariables
}

And then, I extend this class like following:

case class Derived (a: SomeOtherClass, i: Int) extends Base {
//Do something with a
} 

Then, I have a method (independent of classes) that is as follows:

 def myMethod (v1: Base, v2: Base, f:(Base, Base) => Int ): Int

And I want to use the above method as myMethod(o1, o2, f1), where

  1. o1, o2 are objects of type Derived
  2. f1 is as follows def f1(v1: Derived, v2: Derived): Int

Now, this gives me an error because myMethod expects the function f1 to be (Base, Base) => Int, and not (Derived, Derived) => Int. However, if I change the definition of f1 to (Base, Base) => Int, then it gives me an error because internally I want to use some variable from SomeOtherClass, an argument that Base does not have.


Solution

  • According to my (very simple) tests, this change...

    def myMethod[B <: Base](v1: Base, v2: Base, f:(B, B) => Int ): Int = ???
    

    ...will allow either of these methods...

    def f1(a: Derived, b:Derived): Int = ???
    def f2(a: Base, b:Base): Int = ???
    

    ...to be accepted as a passed parameter.

    myMethod(Derived(x,1), Derived(x,2), f1)
    myMethod(Derived(x,1), Derived(x,2), f2)