相关疑难解决方法(0)

具有另一类自我类型的类是否有意义?

scala> class A
defined class A

scala> class B {this: A => }
defined class B

scala> new B
<console>:10: error: class B cannot be instantiated because it does not conform
to its self-type B with A
             new B
             ^
Run Code Online (Sandbox Code Playgroud)

B将self类型设置为class A,因此class B(或它的子类)必须扩展类A以创建实例B.但这有可能,因为一个子类B只能扩展一个类(这是类B)?

所以这引出了我的问题,在任何情况下将类的自我类型声明为另一个类是否有意义?

scala self-type

6
推荐指数
1
解决办法
1112
查看次数

在什么情况下,自我类型注释提供了不可能使用extends的行为

我试图想出一个合成场景,其中自我类型和扩展行为不同,到目前为止还没有找到一个.基本示例总是讨论一种自我类型,不要求类/特征不必是依赖类型的子类型,但即使在那种情况下,自我类型和扩展之间的行为似乎是相同的.

trait Fooable { def X: String }
trait Bar1 { self: Fooable =>
  def Y = X + "-bar"
}
trait Bar2 extends Fooable {
  def Y = X + "-bar"
}
trait Foo extends Fooable {
  def X = "foo"
}
val b1 = new Bar1 with Foo
val b2 = new Bar2 with Foo
Run Code Online (Sandbox Code Playgroud)

是否存在某种形式的组合对象的某种形式的组合或功能在使用一种与另一种时不同的情况?

更新1:感谢没有自我键入的事情的例子,我很欣赏这些信息,但我真的在寻找自我和扩展可能的组合,但不可互换.

更新2:我想我遇到的具体问题是为什么各种Cake Pattern示例通常都会讨论必须使用self-type而不是extends.我还没有找到一个与扩展无关的Cake Pattern场景

extends scala self-type cake-pattern

4
推荐指数
1
解决办法
149
查看次数

标签 统计

scala ×2

self-type ×2

cake-pattern ×1

extends ×1