Thursday 11 June 2015

Implicit Arguments / Conversion

An implicit parameter is a parameter to method or constructor that is marked as implicit. This means that if a parameter value is not supplied then the compiler will search for an "implicit" value defined within scope (according to resolution rules.) Implicit parameter resolution rules will be discussed soon.

The benefits of Implicit arguments:
1. Boilerplate elimination, such as providing context information implicitly rather than explicity
2. Constrains that reduce bugs or limit the allowed types that can be used with certain methods with parameterized types.

Rules for Implicit arguments:
1. Only the last argument list, including the only list for a single-list method, can have implicit arguments.
2. The implicit keyword must appear first and only once in the argument list. The list can't have "nonimplicit"
arguments followed by implicit arguments.
3. All the arguments are implicit when the list starts with the implicit keyword.


Example:

  1. scala> def p(implicit i:Int) = print(i)
  2. p: (implicit i: Int)Unit
  3. // defining a val/var/def as implicit 
  4. // means that it will be considered during implicit resolution
  5. scala> implicit val v=2
  6. v: Int = 2
  7. // scope is searched for a implicit value to sue
  8. // v is found as marked implicit
  9. scala> p               
  10. 2
  11. // explicit declarations always overrides implicit values
  12. scala> p(1)
  13. 1
Implicit Conversion

For something to be considered an implicit conversion, it must be declared with the implicit keyword and it must either be a class that takes a single constructor argument or it must be a method that takes a single argument. For example,

implicit final class ArrowAssoc[A](val self:A){
    def => [B](y:B): Tuple2[A,B] = Tuple2(self, y)
}

Enable the implicit conversion feature by: import scala.language.implicitConversions
Here is a summary of the lookup rules used by the compiler to find and apply conversions methods:

1. No conversion will be attempted if the object and method combination type check successfully.
2. Only classes and methods with the implicit keyword are considered.
3. Only implicit classes and methods in the current scope are considered, as well as implicit methods defined in the companion object of the target type.
4. Implicit methods aren't chained to get from the available type. Only a method that takes a single available type instance and returns a target type instance will be considered.
5. No conversion is attempted if more than one possible conversion method could be applied.


No comments:

Post a Comment