【问题标题】:Can Scala method that returns a trait returns method with the same type as trait?返回特征的Scala方法可以返回与特征相同类型的方法吗?
【发布时间】:2021-06-14 20:14:12
【问题描述】:

我正在尝试编写如下所示的内容:

trait interface {
   getA(a:_): trA 
}

trait trA extends (x => y)

特征的实现如下:

object obX extends interface {
   override def getA(a:_): x => y = X => ???
}

但是,我得到了错误

Overriding type a => x => y does not conform to base type a => trA

即使trA 接受x => y。有没有办法解决这个问题?是我修改 trait 接口的唯一选择,例如:

 trait interface {
   getA(a:_): x => y
}

提前致谢!

【问题讨论】:

  • 我建议您阅读更多关于继承的内容。也可以提供一些具体的代码,以便我们最终了解您的目标。例如,这里trA 没有任何价值。

标签: scala interface traits


【解决方案1】:

即使trA 接受x => y

这是错误的。 trAx => y,但相反的情况为真:x => y 不是trAtrA 不能从 x => y 构建。

您使用比interface 允许的更广泛的返回类型定义您的obX

【讨论】:

    【解决方案2】:

    例如,如果您可以使 trA 不扩展 x => y 而是这样,您的代码将编译

    type trA = x => y
    

    否则你可以引入一个类型

    trait interface {
      type Out >: trA
      def getA(a: _): Out
    }
    
    object obX extends interface {
      type Out = x => y
      override def getA(a: _): x => y = X => ???
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      • 1970-01-01
      • 2018-03-11
      • 1970-01-01
      • 2017-09-05
      • 2016-05-13
      相关资源
      最近更新 更多