O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

A strategy in Scala land

By now you must have guessed that in Scala, things are far simpler. Let's try the following commands with creating an object:

object MovieStrategy extends App {

  type MoviePref = () => String // 1

  abstract class FamilyMember {
    def name: String
    def moviePref: MoviePref
  }

  case class Mom(name: String, moviePref: MoviePref) extends
    FamilyMember
  case class Dad(name: String, moviePref: MoviePref) extends
    FamilyMember
  case class Kid(name: String, moviePref: MoviePref) extends
    FamilyMember

  def letUsGoForAMovie[T <: FamilyMember](familyMember: T) = { // 2
    val mp = s"${familyMember.name} :  ${familyMember
      .moviePref() } "
    println(mp)
  }

  val mom = Mom("Mom", () => "some romantic flick") // 3
 val dad = Dad("Dad", () ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required