Tuesday 19 August 2014

Scala Note 11: Implicit keyword


1. Implicit parameters

The principal idea behind implicit parameters is that arguments for them can be left out from a method call. The final parameter list on a method can be marked implicit, which means the values will be taken from the context(inferred by the scala compiler) in which they are called.  If such a method misses arguments for its implicit parameters, such arguments will be automatically provided.

class PreferredPrompt(val preference: String)
object Greeter {
    def greet(name: String)(implicit prompt: PreferredPrompt) {
      println("Welcome, "+ name)
      println(prompt.preference)
    }
  }

implicit val prompt = new PreferredPrompt("Yes, master")

scala> Greeter.greet("Joe")  //miss prompt argument
Welcome, Joe.
Yes, master



2. Implicit conversions


When the compiler finds an expression of the wrong type for the context, it will look for an implicit Functionvalue of a type that will allow it to typecheck. So if a type A is required and it finds a type B, it will look for an implicit value of type B => A in scope.

Implicits work like this: if you call a method on a Scala object, and the Scala compiler does not see a definition for that method in the class definition for that object, then the compiler will try to convert your object to an instance of a class that does have that method defined.

So the difference between your methods is that the one marked implicit will be inserted for you by the compiler when a Double is found but an Int is required.
scala> implicit def doubleToInt(d:Double) = d.toInt
scala> val x: Int = 42.0
x: Int = 42



Reference:
http://stackoverflow.com/questions/10375633/understanding-implicit-in-scala



No comments:

Post a Comment