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

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

问题描述

为什么下面的方法不起作用?

Why don't the following work?

scala> abstract class Foo[B<:Foo[B]]
defined class Foo

scala> class Goo[B<:Foo[B]](x: B)
defined class Goo

scala> trait Hoo[B<:Foo[B]] { self: B => new Goo(self) }
<console>:9: error: inferred type arguments [Hoo[B] with B] do not conform to class Goo's type parameter bounds [B <: Foo[B]]
       trait Hoo[B<:Foo[B]] { self: B => new Goo(self) }
                                         ^

scala> trait Hoo[B<:Foo[B]] extends Foo[B] { new Goo(this) }
<console>:9: error: inferred type arguments [Hoo[B]] do not conform to class Goo's type parameter bounds [B <: Foo[B]]
       trait Hoo[B<:Foo[B]] extends Foo[B] { new Goo(this) }
                                             ^

在第一次尝试中,不是 Hoo[B] with B <: Foo[B] 吗?

In the first attempt, isn't Hoo[B] with B <: Foo[B]?

在第二次尝试中,不是 Hoo[B] <: Foo[B] 吗?

In the second attempt, isn't Hoo[B] <: Foo[B]?

为了激发这个问题,有一个库:

To motivate this problem, there's a library with:

// "Foo"
abstract class Record[PK, R <: Record[PK, R]] extends Equals { this: R =>
  implicit def view(x: String) = new DefinitionHelper(x, this)
  ...
}
// "Hoo"
class DefinitionHelper[R <: Record[_, R]](name: String, record: R) {
  def TEXT = ...
  ...
}

// now you can write:
class MyRecord extends Record[Int, MyRecord] {
  val myfield = "myfield".TEXT
}

我正在尝试在 TEXT 旁边引入一种名为 BYTEA 的新扩展方法,以便人们可以编写:

I'm trying to introduce a new extension method alongside TEXT called BYTEA, so that one can write:

class MyRecord extends XRecord[Int, MyRecord] {
  val myfield = "myfield".BYTEA // implicit active only inside this scope
}

我的尝试:

class XDefinitionHelper[R <: Record[_, R]](name: String, record: R) {
  def BYTEA = ...
}

trait XRecord[PK, R <: Record[PK, R]] { self: R =>
  implicit def newView(x: String) = new XDefinitionHelper(x, self)
}

但这与我上面的较小测试用例遇到了相同的问题.

But this runs into the same problems as my smaller test case above.

推荐答案

在第一次尝试中,您确实有 Hoo[B] 和 B <: Foo[B].但是要使 Goo[Hoo[B] with B] 存在,您需要 Hoo[B] with B <: Foo[Hoo[B] with B].第二种情况类似.

In the first attempt, you do have Hoo[B] with B <: Foo[B]. But for Goo[Hoo[B] with B] to exist, you need Hoo[B] with B <: Foo[Hoo[B] with B]. Similarly in the second case.

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

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