SCALA IMPLICIT

  • date 18th February, 2021 |
  • by Prwatech |
  • 0 Comments

Implicit Parameters

Implicit parameters are similar to regular method parameters, except they could be passed to a method silently without going through the regular parameters list.

A method can define a list of implicit parameters that are placed after the list of regular parameters. These parameters are indicated using the implicit keyword, and all parameters after the implicit keyword are implicit:

When a method is defined with implicit parameters, Scala will look up implicit values in the scope by matching the type if they are not already passed in the implicit parameter list.

Implicit conversions

When the compiler finds an expression of the wrong type for the context, it will look for an implicit Function value of a type that will allow it to type check. So if an A is required and it finds a B, it will look for an implicit value of type B => An in scope (it also checks some other places like in the B and A companion objects, if they exist). Since defs can be “eta-expanded” into Function objects, implicit def XYZ ( arg: B): A will do as well.

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.

Types Class

A type class is a group of types that satisfy a contract typically defined by a trait. They enable us to make a function more ad-hoc polymorphic without touching its code. This flexibility is the biggest win with the type-class pattern.

A type class is a type system construct that supports ad hoc polymorphism. This is achieved by adding constraints to type variables in parametrically polymorphic types. Such a constraint typically involves a type class T and a type variable a, and means that a can only be instantiated to a type whose members support the overloaded operations associated with T

This is achieved by adding constraints to type variables in parametrically polymorphic types. In our case, the type class above is the parametrically polymorphic type since we defined it with an unbounded type A, meaning we can substitute A with any type when extending it.

Quick Support

image image