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:
- scala> def p(implicit i:Int) = print(i)
- p: (implicit i: Int)Unit
- // defining a val/var/def as implicit
- // means that it will be considered during implicit resolution
- scala> implicit val v=2
- v: Int = 2
- // scope is searched for a implicit value to sue
- // v is found as marked implicit
- scala> p
- 2
- // explicit declarations always overrides implicit values
- scala> p(1)
- 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