2015-06-18 161 views
7

有沒有辦法定義一個通用型的替代品的集合:斯卡拉 - 相互排斥的特質

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 

是否有一種更直接的方式來表達這種約束,並且不允許某人通過採用編譯器提供的提示來解決此問題(重寫帽子中的'衝突')?

感謝任何見解

+0

這實現了什麼目標?我不記得任何時候我曾經想這樣做.. – Daenyth

+0

首先,感謝下面的想法,仍然在思考我是否可以得到一個密封的解決方案(這不允許太容易的錯誤「 MutabilityLevel [Mutability]「滑過)。二,關於目標。目標有兩個層次:(1)標記特徵來指示處理程序,它們可以安全地不處理此類型實例的更新事件;(2)實際擴展可變特徵以定義這些事件: class Events [T <:Mutable ] { case class Add(T) case class Remove(T) }例如。 – jmcnulty

+0

'class Mat(name:String)extends Mutable' 'class Pat extends Immutable' 處理程序可以安全地假定對象PatEvents擴展Events [Pat]'無法編譯並且'PatEvents.Add/Remove'不存在 – jmcnulty

回答

3

我想這可能工作

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 
+0

可以通過密封'MutabilityLevel'並添加另一個級別來解決這個問題,例如'不變的特質擴展MutabilityLevel [MutabilityLevel.I]'。 –

+0

@JCracknell調用者然後可以擴展Immutable並給它不適當的實現。 – Daenyth

+0

是的,但是它會阻止創建'MutabilityLevel [Mutability]'。 –