蛋糕模式和类型

时间:2012-05-31 09:57:43

标签: scala types cake-pattern

def someA {在trait Btrait A如何使用与C#MyType相同的B A#MyType =:= B#MyType? (然后trait C { type MyType } trait A { self: C => def doSomething(s: MyType) { println(s.toString)} } trait B { self: C => def someA: A def myType: MyType def action = someA.doSomething(myType) } // Mix part case class Ahoy(value: String) trait ConcreteC extends C { type MyType = Ahoy } class PieceOfCake extends B with ConcreteC { val someA = new A with ConcreteC val myType = Ahoy("MyType") }

[error]  found   : B.this.MyType
[error]  required: _1.MyType where val _1: A
[error]   def action = someA.doSomething(myType))

它不编译:类型不匹配;

{{1}}

2 个答案:

答案 0 :(得分:3)

您可以声明doSomethingmyType使用与路径无关的版本MyTypeSomeType#MyType

trait SomeType {
  type MyType
}


trait A {
  self: SomeType =>
  def doSomething(s: SomeType#MyType) { println(s.toString)}
}

trait B {
  self: SomeType =>  

  def someA: A
  def myType: SomeType#MyType

  def action = someA.doSomething(myType)
}

答案 1 :(得分:0)

我很确定你不能这样做,因为与路径无关的类型只是 - 如果A<> B然后A#T与B#T严格不同(即A#T将永远 = =:= B#T)。

话虽如此,施放是安全的,所以你总是可以做someA.doSomething(myType.asInstanceOf[someA#MyType])之类的事情。丑陋但有效。