返回 trait 的 Scala 方法可以返回与 trait 类型相同的方法吗?

时间:2021-06-14 20:14:12

标签: scala interface traits

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

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
}

提前致谢!

2 个答案:

答案 0 :(得分:1)

<块引用>

即使 trA 接受 x => y

这是错误的。 trAx => y,但反之 not 为真:x => y nottrA。不能从 trA 构建 x => y

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

答案 1 :(得分:0)

例如,如果您可以使 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 => ???
}