简体   繁体   中英

Cake Pattern in Scala

I was trying to convert my understanding about cake patterns in to simple scala code and found out that its not compiling. Could some one please have a look at the below code and tell me whats the problem in the way I understand the patterns? I read this article and was trying out something similar( http://www.cakesolutions.net/teamblogs/2011/12/19/cake-pattern-in-depth )

Here in the code below - println("This is " + userServiceComponent.whatCalc1) //> This is () - I was expecting it to print This is ScifiCalc Calc but its printing This is ()

Code:-

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 ()
}

Scala is not a dynamic language, it is statically typed. When you made this declaration in trait Calc :

def whatCalc

the absence of a type led Scala to default it's type to Unit . When this method got overridden, the type stayed Unit , so the string values were discarded. Unit has a single instance, which is () , so that's what is being printed.

If you change that line to def whatCalc: String , it should work fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM