Implicit Conversions in Scala


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:

  • First, if an expression of type A and S does not match to the expected expression type B.
  • Second, in a selection e.m of expression e of type A, if the selector m does not represent a member of A.

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 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of implicit conversions
import A.fromString
import scala.language.implicitConversions
   
case class A(s: String)
object A
{
    // Using implicitConversions    
    implicit def fromString(s: String): A = A(s)
}
   
class
{
  def m1(a: A) = println(a)
  def m(s: String) = m1(s)
}
   
// Creating object
object
{
    // Main method
    def main(args: Array[String])
    {
        var b : A = ("GeeksforGeeks")
         println(b) 
       
    }
}

chevron_right


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:

  • Import scala.language.implicitConversions into the scope of the implicit conversion definition.
  • Invoke the compiler with -language:implicitConversions.

Now, let’s look at an another example.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of implicit conversions
import ComplexImplicits._
  
object ComplexImplicits
{
    // implicit conversion
    implicit def DoubleComplex(value : Double) = 
                        new Complex(value,0.0)
      
    implicit def TupleComplex(value : Tuple2[Double,Double]) = 
                        new Complex(value._1,value._2);
  
}
  
// Creating a class containg different method
class Complex(val r : Double, val i : Double) 
{
      
    def +(that: Complex) : Complex = 
    (this.r + that.r, this.i + that.i)
      
    def -(that: Complex) : Complex = 
    (this.r - that.r, this.i + that.i)
          
    def unary_~ = Math.sqrt(r * r + i * i)
          
    override def toString = r + " + " + i + "i"
      
}
  
// Creating Onject
object Complex 
{
      
val i = new Complex(0,1);
  
// Main method    
def main(args : Array[String]) : Unit =
{
    var a : Complex = (6.0,4.0)
    var b : Complex = (1.0,2.0)
    println(a) 
    println(a + b) 
    println(a - b) 
    println(~b) 
          
    var c = 5 + b
    println(c) 
    var d = (3.0,3.0) + c 
    println(d) 
}
}

chevron_right


Output :

6.0 + 4.0i
7.0 + 6.0i
5.0 + 6.0i
2.23606797749979
6.0 + 2.0i
9.0 + 5.0i


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.