理解 Scala 中的“推断类型参数不符合类型参数边界"错误 [英] Understanding “inferred type arguments do not conform to type parameter bounds” errors in Scala

查看:53
本文介绍了理解 Scala 中的“推断类型参数不符合类型参数边界"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么我会收到推断的类型参数不符合类型参数界限".首先,我定义了一个称为 CS 的特性,它可以由多个类(例如 CS01 和 CS02)实现:

I fail to understand why I am getting an "inferred type arguments do not conform to type parameter bounds". First, I defined a trait called CS which may be implemented by several classes (e.g., CS01 and CS02):

trait CS[+T <: CS[T]] {
  this: T =>
  def add: T
  def remove: T
}

class CS01 extends CS[CS01] {
  def add: CS01 = new CS01
  def remove: CS01 = new CS01
}

class CS02 extends CS[CS02] {
  def add: CS02 = new CS02
  def remove: CS02 = new CS02
}

这个想法是在 CS01 和 CS02 上调用 addremove 时保持实现的类型.其次,我想定义可以在每个符合 trait CS 的类上执行的操作.然后,我定义了一个名为 Exec 的 trait(有两个非常简单的例子,Exec01Exec02 混入了 Exec特质):

The idea is to keep the implemented type when calling add or remove on CS01 and CS02. Secondly, I would like to define operations that may be executed on every classes compliant with trait CS. Then, I defined a trait called Exec(with two very simple examples of classes Exec01 and Exec02 mixin the Exec traits):

trait Exec {
  def exec[U <: CS[U]](x: U): U
}

class Exec01 extends Exec {
  def exec[U <: CS[U]](x: U): U = x.add
}

class Exec02 extends Exec {
  def exec[U <: CS[U]](x: U): U = x.remove
}

再一次,我需要保留混合了 CS 特性的类的实现类型.这就是为什么 exec 被参数化为 [U <: CS[U]].

Once again, I need to keep the implemented type of the class that mixes the CS trait. That is why exec is parametrized with [U <: CS[U]].

最后,我希望任何 CS 能够对其进行操作以混合特征 Executable,这使得执行遵循特征 Exec 的操作成为可能>:

Finally, I want any CS enabling operations on it to mixin the trait Executable which makes it possible to execute an operation that follows trait Exec:

trait Executable[T <: CS[T]] {
  this: T =>
  def execute(e: Exec): T = e.exec(this)
}

但是,当我尝试编译时出现以下错误:

However, I get the following error when I am trying to compile:

error: inferred type arguments [this.Executable[T] with T] do not conform to method exec's type parameter bounds [U <: this.CS[U]]
  def execute(e: Exec): T = e.exec(this)
                              ^

我不太明白,因为任何混合 Executable 的类都必须是 T 类型,并且由于 中的限制而具有混合 CS 特征的约束trait Executable[T <: CS[T]].那么,为什么 this 不符合类型参数绑定 U <: CS[U] ?

I don't quite understand because any classes that mix Executable must be of type T with the constraint of mixin the CS trait due to the bound in trait Executable[T <: CS[T]]. So, why this does not conform to the type parameter bound U <: CS[U] ?

推荐答案

如果您显式指定类型参数来执行:

Works if you specify the type parameter to exec explicitly:

def execute(e: Exec): T = e.exec[T](this)

似乎是类型推断的限制.

Seems to be a limitation in the type inference.

这篇关于理解 Scala 中的“推断类型参数不符合类型参数边界"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆