【问题标题】:refer to object type in object definition在对象定义中引用对象类型
【发布时间】:2013-07-28 17:31:48
【问题描述】:

注意:第一个示例有效。它显示了我想要得到的东西。第二个例子表明我想在没有样板的情况下声明它,但没有这样做。


我只想简单点:

trait SelfTest[T <: SelfTest[T]] {_ : T =>
  def get : T = this
}
class Test extends SelfTest[Test]
object Test extends Test

但没有样板类定义。像这样的:

trait SelfTest[T <: SelfTest[T]] {_ : T =>
  def get : T = this
}
object Test extends SelfTest[Test.type]

但这种方式被 scala (illegal cyclic reference involving object Test) 拒绝。有没有像# 这样的魔法来表示创建的对象?

【问题讨论】:

  • 您使用的是哪个版本的 Scala 编译器?您的代码的第一个版本在 Scala 2.10.2 下运行良好
  • 2.9.2、2.10.0。我想用第二个。它更短并且不会创建冗余实体。问题是关于如何在不定义类的情况下实现第一个示例的效果,就像它应该在第二个中那样

标签: scala generics


【解决方案1】:

这在 scala 2.10 控制台中有效::

scala> trait SelfTest[T<:SelfTest[_]] {_: T => def get:T = this }
defined trait SelfTest

scala> class Test extends SelfTest[Test]
defined class Test

scala> case object t extends Test
defined module t

scala> t.get
res1: Test = t

【讨论】:

  • 这对我也有用。但问题是如何消除多余的class 声明。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-02
  • 2020-04-21
  • 2022-11-12
  • 1970-01-01
相关资源
最近更新 更多