Polymorphic Scala return type

后端 未结 2 1235
我在风中等你
我在风中等你 2020-12-14 12:54

I have an abstract Scala class Base which has subclasses Derived1 and Derived2. Base defines a function f() which returns

2条回答
  •  悲哀的现实
    2020-12-14 13:09

    Randall Schulz pointed out one of the reasons your current code doesn't work. It is possible to get what you want, though, with F-bounded polymorphism:

    trait Base[C <: Base[C]] { def f: C }
    
    case class Derived1(x: Int) extends Base[Derived1] {
      def f: Derived1 = Derived1(x + 1)
    }
    
    case class Derived2(x: Int) extends Base[Derived2] {
      // Note that you don't have to provide the return type here.
      def f = Derived2(x + 2)
    }
    

    The type parameter on the base trait allows you to talk about the implementing class there—e.g. in the return type for f.

提交回复
热议问题