斯卡拉蛋糕模式

时间:2014-08-03 01:18:10

标签: scala cake-pattern

我试图将我对蛋糕模式的理解转换为简单的scala代码,并发现它没有编译。有人可以看看下面的代码,并告诉我这是什么方式我理解模式的问题?我读了这篇文章,并尝试了类似的东西(http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth

以下代码中显示了println("This is " + userServiceComponent.whatCalc1) //> This is () - 我希望它能打印This is ScifiCalc Calc,但打印This is ()

代码: -

trait Calc {
  def whatCalc
}

trait NormalCalc extends Calc {
  def whatCalc = new String("Normal Calc")
}

trait ScifiCalc extends Calc {
  def whatCalc = new String("ScifiCalc Calc")
}

trait TestTrait{
  def whatCalc1
}

trait TestCalc extends TestTrait {  
  this: Calc =>;

  def whatCalc1 = {
    whatCalc
  }
}

object SelfReferenceExample {
  println("Welcome to the Scala worksheet") 
  val userServiceComponent = new TestCalc with ScifiCalc {}
  println("This is " + userServiceComponent.whatCalc1) //> This is ()
}

1 个答案:

答案 0 :(得分:8)

Scala不是动态语言,它是静态类型的。当您在特征Calc

中进行此声明时
def whatCalc

缺少类型导致Scala将其类型默认为Unit。当重写此方法时,类型保持Unit,因此字符串值被丢弃。 Unit有一个实例,即(),这就是正在打印的内容。

如果您将该行更改为def whatCalc: String,它应该可以正常工作。

相关问题