Scala Patterns – Cake Pattern

May - 19 2016 | By

I think its about time i started jotting down some of the patterns I’m starting to utilise in Scala.

For both myself and other s to gain insight from.

 

Here is something i put together

package Training
import org.scalatest.{Matchers, FlatSpec}
import scala.collection.mutable

//Animal Type so we can see waht we have selected in the test
object AnimalType {
  final val Dog : String = "Dog"
final val Kangaroo : String = "Kangaroo"
}

//trait to get / set food listing
trait FoodAteToday {
  def AteFood(food: String)
  def GetListOfFood(): Array[String]
}


//generic Trait
trait Animal {
  def GetNumberOfLegs(): Integer
  def GetAnimalType() : String
def Food : FoodAteToday
}

//more specific but still generic with singleton
trait Dog extends Animal {
  def Food = DogFoodDiet

  def GetNumberOfLegs() = 4
def GetAnimalType() = AnimalType.Dog

//create a singleton object inside our trait so that we can link our Dog trait to a single Food Object.
object DogFoodDiet extends FoodAteToday {
    var foodList = new mutable.ArrayBuffer[String]()

    override def AteFood(food: String): Unit = foodList += food
    override def GetListOfFood(): Array[String] = foodList.toArray
  }

}

//more specific but still generic with singleton
trait Kangaroo extends Animal
{
  def Food = KangarooFoodDiet

  def GetNumberOfLegs() = 2
def GetAnimalType() = AnimalType.Kangaroo

//create a singleton object inside our trait so that we can link our Dog trait to a single Food Object.
object KangarooFoodDiet extends FoodAteToday {
    var foodList = new mutable.ArrayBuffer[String]()

    override def AteFood(food: String): Unit = foodList += food

    override def GetListOfFood(): Array[String] = foodList.toArray
  }
}



trait Trainer{
  this: Animal => // what kind of animal do I train
}

class AnimalTraining extends FlatSpec
  with Matchers
  {

  it should "call a Dog" in {

    val myDog = new Trainer() with Dog
    println(s"My Dog has " + myDog.GetNumberOfLegs() + " legs")
    myDog.Food.AteFood("shoe")
    myDog.Food.AteFood("bone")

    println(s"My Dog ate " + myDog.Food.GetListOfFood().mkString(" & ") + " today")

  }

  it should "call a Kangaroo" in {

    val myKangaroo = new Trainer() with Kangaroo
    println(s"My Kangaroo has " + myKangaroo.GetNumberOfLegs() + " legs")
    myKangaroo.Food.AteFood("grass")
    myKangaroo.Food.AteFood("leaves")
    println(s"My Kangaroo ate " + myKangaroo.Food.GetListOfFood().mkString(" & ") + " today")

  }
}
 

 

Of Course the output of this is

My Dog has 4 legs
My Dog ate shoe & bone today
My Kangaroo has 2 legs
My Kangaroo ate grass & leaves today

 

 

Comments are closed. Please see front page on how to contact me