guangningyu
11/9/2017 - 2:52 AM

source: https://stackoverflow.com/questions/10375633/understanding-implicit-in-scala

object HelloWorld {
  case class Text(content: String)
  case class Prefix(text: String)

  // step 2: capture the String conversion in implicit function;
  //         then find an implicit parameter and end up with finding "prefixLOL"
  implicit def String2Text(content: String)(implicit prefix: Prefix) = {
    // step 3: return instance of Text
    Text(prefix.text + " " + content)
  }

  // step 1: need to convert "String" to "Text"
  def printText(text: Text): Unit = {
    // step 4: print content
    println(text.content)
  }

  def main(args: Array[String]): Unit = {
    printText("World!")
  }

  // step 0: initialize an implicit instance of class Prefix
  implicit val prefixLOL = Prefix("Hello")
}