Sunday, October 18, 2015

Implicit parameter

Implicit parameter saves you the trouble of providing a (locally) fixed value to some method over and over again, resulting in more concise code.

object Example {
  class PreferredPrompt(val preference: String)
  def greet(name: String)(implicit prompt: PreferredPrompt): Unit = {
    println("Welcome, Scala user: " + name + ". ")
    println(prompt.preference)
  }
  implicit val prompt = new PreferredPrompt("Yes, master> ")
}


object Test {
  import Example._
  greet("Victor")
}

Another example with two implicit parameters:

object Example {
  class PreferredPrompt(val preference: String)
  class PreferredDrink(val preference: String)
  def greet(name: String)(implicit prompt: PreferredPrompt, drink: PreferredDrink): Unit = {
    println("Welcome, Scala user: " + name + ". ")
    println("The system is ready. But while you work, why not enjoy a cup of " + drink.preference + "?")
    println(prompt.preference)
  }
  implicit val prompt = new PreferredPrompt("Yes, master> ")
  implicit val drink = new PreferredDrink("tea")
}


object Test {

  import Example._

  greet("Victor")
}

0 comments: