![]() |
VOOZH | about |
Implicit conversions in Scala are the set of methods that are apply when an object of wrong type is used. It allows the compiler to automatically convert of one type to another.
Implicit conversions are applied in two conditions:
In the first condition, a conversion is searched which is appropriate to the expression and whose result type matches to B. In the second condition, a conversion is searched which appropriate to the expression and whose result carries a member named m.
Now, let us understand with an example.
The following operation on the two lists xa and ya of type List[Int] is legal:
xa = ya
Suppose the implicit methods listorder and intorder are defined below in the scope:
implicit def listorder[A](x: List[A])
(implicit elemorder: A => Ordered[A]): Ordered[List[A]] =
new Ordered[List[A]] { /* .. */ }
implicit def intorder(x: Int): Ordered[Int] =
new Ordered[Int] { /* .. */ }
Lets look at an example.
Example :
Output :
A(GeeksforGeeks)
Implicit conversion has a drawback if it is used randomly, the compiler warns when compiling the implicit conversion definition.
To avoid the warnings, we need to take either of these two steps:
Now, let's look at an another example.
Example :
Output :
6.0 + 4.0i 7.0 + 6.0i 5.0 + 6.0i 2.23606797749979 6.0 + 2.0i 9.0 + 5.0i