gpt4 book ai didi

scala - Scala —互斥的特征

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

有没有一种方法可以定义一组常见类型的替代项:

trait Mutability
trait Mutable extends Mutability
trait Immutable extends Mutability

并让编译器排除类似以下内容的情况:
object Hat extends Mutable with Immutable

我相信我可以通过拥有一个通用的,冲突的成员来强制执行一些编译器错误,但是错误消息有点儿斜:
trait Mutability
trait Mutable extends Mutability { protected val conflict = true }
trait Immutable extends Mutability { protected val conflict = true }

object Hat extends Mutable with Immutable

<console>:10: error: object Hat inherits conflicting members:
value conflict in class Immutable$class of type Boolean and
value conflict in class Mutable$class of type Boolean
(Note: this can be resolved by declaring an override in object Hat.)
object Hat extends Immutable with Mutable

有没有更直接的方法来表达此约束,而不允许某人通过采用编译器提供的提示来解决该约束(在Hat中覆盖“冲突”)?

感谢您的任何见解

最佳答案

我认为这可能有效

sealed trait Mutability
case object Immutable extends Mutability
case object Mutable extends Mutability

trait MutabilityLevel[A <: Mutability]

class Foo extends MutabilityLevel[Immutable.type]

(ab?)使用以下事实:您无法使用不同的参数化来扩展相同的特征两次
scala> class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]
<console>:11: error: illegal inheritance;
self-type Foo does not conform to MutabilityLevel[Immutable.type]'s selftype MutabilityLevel[Immutable.type]
class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]
^
<console>:11: error: illegal inheritance;
self-type Foo does not conform to MutabilityLevel[Mutable.type]'s selftype MutabilityLevel[Mutable.type]
class Foo extends MutabilityLevel[Immutable.type] with MutabilityLevel[Mutable.type]

然而..
scala> class Foo extends MutabilityLevel[Mutability]
defined class Foo

关于scala - Scala —互斥的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30926360/

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