I have a trait A
which has a method def fun1( b:B ):C
I want A
's subclass implement B with more detailed type:
Here is the code:
trait B
trait C
trait A {
def fun1( b:B ):C
}
class B1 extends B{
}
class B2 extends B{
}
class C1 extends C{
}
class C2 extends C{
}
I hope A
's subclass can be declared as below
class X1 extends A{
override def fun1(b:B1):C1 = ...
}
class X2 extends A{
override def fun1(b:B2):C2 = ...
}
However, the compiler will complain that X1 overrides nothing
. I have to manually match detailed B
's type, like below.
class X1 extends A{
override def fun1(b:B):C = b match {case x:B1 => ... }
}
class X2 extends A{
override def fun1(b:B2):C2 = b match {case x:B2 => ... }
}
This method cannot check the correct type during compiling. How can I achieve the first implementation? Is there any design pattern to handle this problem?
A similar question is C# Override method with subclass parameter
Aucun commentaire:
Enregistrer un commentaire