首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >斯卡拉-相互排斥的特性

斯卡拉-相互排斥的特性
EN

Stack Overflow用户
提问于 2015-06-18 21:47:35
回答 1查看 436关注 0票数 8

是否有一种方法可以定义公共类型的可选方案的集合:

代码语言:javascript
复制
trait Mutability
trait Mutable extends Mutability
trait Immutable extends Mutability

并让编译器排除如下内容:

代码语言:javascript
复制
object Hat extends Mutable with Immutable

我相信我可以通过有一个共同的、相互冲突的成员来强制一些编译器错误,但是错误信息有点偏斜:

代码语言:javascript
复制
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中覆盖‘冲突’)来绕过它呢?

谢谢你的见解

EN

回答 1

Stack Overflow用户

发布于 2015-06-18 22:21:04

我觉得这可能有用

代码语言:javascript
复制
sealed trait Mutability
case object Immutable extends Mutability
case object Mutable extends Mutability

trait MutabilityLevel[A <: Mutability]

class Foo extends MutabilityLevel[Immutable.type]

这个(ab?)使用的事实是,不能用不同的参数化两次扩展相同的特性。

代码语言:javascript
复制
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]

但是..。

代码语言:javascript
复制
scala> class Foo extends MutabilityLevel[Mutability]
defined class Foo
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30926360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档