gpt4 book ai didi

scala - 蛋糕图案 : mixing in in a trait

转载 作者:行者123 更新时间:2023-12-04 20:08:18 25 4
gpt4 key购买 nike

我一直在玩蛋糕图案,有些东西我不完全理解。

给定以下通用代码:

trait AServiceComponent {
this: ARepositoryComponent =>
}

trait ARepositoryComponent {}

以下混合它们的方法有效
trait Controller {
this: AServiceComponent =>
}

object Controller extends
Controller with
AServiceComponent with
ARepositoryComponent

但以下不
trait Controller extends AServiceComponent {}

object Controller extends
Controller with
ARepositoryComponent

有错误:
illegal inheritance; self-type Controller does not conform to AServiceComponent's selftype AServiceComponent with ARepositoryComponent

如果我们知道它们对所有子类都是通用的,我们难道不应该能够在层次结构中“推送”依赖关系吗?

编译器不应该允许 Controller有依赖关系,只要它没有解决它们就没有实例化?

最佳答案

这是遇到相同问题的一种稍微简单的方法:

scala> trait Foo
defined trait Foo

scala> trait Bar { this: Foo => }
defined trait Bar

scala> trait Baz extends Bar
<console>:9: error: illegal inheritance;
self-type Baz does not conform to Bar's selftype Bar with Foo
trait Baz extends Bar
^

问题是编译器希望您在子类型定义中重复自类型约束。在我的简化情况下,我们会写:
trait Baz extends Bar { this: Foo => }

在你的你只需要进行以下更改:
trait Controller extends AServiceComponent { this: ARepositoryComponent => }

这个要求是有道理的——希望有人使用 Controller 是合理的。无需查看它继承的类型即可了解此依赖项。

关于scala - 蛋糕图案 : mixing in in a trait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22662406/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com