Ana*_*and 1 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 ()
}
Run Code Online (Sandbox Code Playgroud)
Scala不是动态语言,它是静态类型的.当您在特征中做出此声明时Calc:
def whatCalc
Run Code Online (Sandbox Code Playgroud)
缺少一个类型导致Scala默认它的类型为Unit.当此方法被覆盖时,类型保持不变Unit,因此字符串值被丢弃.Unit有一个实例,这()就是正在打印的内容.
如果将该行更改为def whatCalc: String,则应该可以正常工作.
| 归档时间: |
|
| 查看次数: |
358 次 |
| 最近记录: |