I have an F-bounded type, and my objective is to create a type-parametrized method in order to be able to reuse it. Here is the example code:
trait FType {
type ThisType <: FType
def deepCopy(): ThisType
}
class ConcreteType extends FType {
override type ThisType = ConcreteType
override def deepCopy(): ConcreteType = this
}
class ConcreteType2 extends FType {
override type ThisType = ConcreteType2
override def deepCopy(): ConcreteType2 = this
}
object FType {
def deepCopy[T <: FType](_type: T): T = {
_type.deepCopy()
}
/* def deepCopy2(c: ConcreteType2): ConcreteType2 = {
c.deepCopy()
}*/
def main(args: Array[String]): Unit = {
//deepCopy2(new ConcreteType2)
}
}
However, the code does not compile. The compiler throws this error:
Error:(29, 19) type mismatch;
found : _type.ThisType
required: T
_type.deepCopy()
I understand that it has something to to with path-dependent types since _type.ThisType
is not the same type as T
.
But how, then, can I take advantage of F-bounded types if the F-bounded type is not exactly the same as the type using the F-bounded type? If the types are not exactly the same, how is that deepCopy2
compiles?
Note: I know I can avoid using type parameters in deepCopy
by using method overloading for each of the concrete types.
In F-bounded types, you'd normally have
ThisType
as a type parameter instead of a type member:Note the difference: in
FType.deepCopy
the compiler knows that the return type of_type.deepCopy()
isT
.You can do the same with type members: