加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala – 相互排斥的特征

发布时间:2020-12-16 19:14:05 所属栏目:安全 来源:网络整理
导读:有没有办法定义一个常见类型的替代品集合: trait Mutabilitytrait Mutable extends Mutabilitytrait Immutable extends Mutability 并让编译器排除类似的东西: object Hat extends Mutable with Immutable 我相信我可以通过拥有一个共同的,冲突的成员来强
有没有办法定义一个常见类型的替代品集合:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读