Scala:抽象类型可以是多个其他类型的子类型吗?

发布于 2024-12-07 19:36:27 字数 372 浏览 0 评论 0原文

鉴于以下 Scala 定义,

abstract class C {
    type T1 <: { def m() : Int }
    type T2 <: { def n() : Int }
}

是否有一种方法可以在 C 中定义第三种类型,该类型被限制为 T1 和 T2 的子类型?例如,

    type T3 <: T1 & T2 // does not compile

在我看来,这不能按书面方式工作的(部分)原因是我无法确定这不会导致非法约束(例如从两个类继承)。因此,一个相关的问题是我是否可以限制 T1 和 T2 以使这合法,例如要求它们都是特征。

Given the following Scala definitions

abstract class C {
    type T1 <: { def m() : Int }
    type T2 <: { def n() : Int }
}

is there a way to define a third type within C that is constrained to be a subtype of both T1 and T2? E.g.

    type T3 <: T1 & T2 // does not compile

It seems to me that (part of) the reason this won't work as written is that I cannot be sure that this will not lead to an illegal constraint (e.g. inheriting from two classes). Thus, a related question would be if I can constrain T1 and T2 so that this would be legal, e.g. requiring that they both be traits.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

喵星人汪星人 2024-12-14 19:36:27

这能满足您的需要吗?

type T3 <: T1 with T2

这并不要求 T1T2 都是特征 - 例如,您可以使用一个特征和一个类来进行有效的实现(无论是哪一个)是哪个)。

如果您尝试定义 C 的具体子类型,其中 T1T2 都是类,那么它将无法编译,所以我不会担心在约束中强制执行此操作。

Does this do what you need?

type T3 <: T1 with T2

This doesn't require T1 and T2 to both be traits - you could make a valid implementation using one trait and a class, for example (it doesn't matter which one is which).

If you tried to define a concrete subtype of C where T1 and T2 were both classes then it would not compile, so I would not worry about enforcing this in the constraint.

哭泣的笑容 2024-12-14 19:36:27

当然可以,但是类型交集写作with,而不是&

abstract class C {
  type T1 <: { def m() : Int }
  type T2 <: { def n() : Int }
  type T3 <: T1 with T2
}

class X extends C {
  trait T1 {def m(): Int}
  class T2 {def n(): Int = 3}
  class T3 extends T2 with T1 {def m(): Int = 5}
}

如果 T1 和 T2 恰好都是类,那么您将无法进行具体的实现

Sure you can, but type intersection is written with, not &.

abstract class C {
  type T1 <: { def m() : Int }
  type T2 <: { def n() : Int }
  type T3 <: T1 with T2
}

class X extends C {
  trait T1 {def m(): Int}
  class T2 {def n(): Int = 3}
  class T3 extends T2 with T1 {def m(): Int = 5}
}

if T1 and T2 happens to be both class, you just won't be able to make a concrete implementation

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文