Search code examples
scalacake-pattern

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

Solution

  • 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.