Implicit Conversions in Scala
Last Updated :
08 Mar, 2022
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 :
Scala
// 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 C
{
def m1(a: A) = println(a)
def m(s: String) = m1(s)
}
// Creating object
object C
{
// Main method
def main(args: Array[String])
{
var b : A = ("GeeksforGeeks")
println(b)
}
}
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 :
Scala
// 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 containing 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 Object
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)
}
}
Output :
6.0 + 4.0i
7.0 + 6.0i
5.0 + 6.0i
2.23606797749979
6.0 + 2.0i
9.0 + 5.0i
Similar Reads
Implicit Parameters In Scala Implicit parameters are the parameters that are passed to a function with implicit keyword in Scala, which means the values will be taken from the context in which they are called. In simpler terms, if no value or parameter is passed to a method or function, then the compiler will look for implicit
2 min read
What is the Scala Identifier "implicitly"? The implicit identifier in Scala is an effective tool for retrieving implicit values that are included in the current scope. When implicit arguments are anticipated, implicit values are those that are indicated with the implicit keyword and may be provided to methods or constructors automatically. G
2 min read
What is Lifting in Scala? Scala is a programming language that is expressive and effective. It permits builders to produce code that is both elegant and succinct. Lifting is one such belonging that is vital to useful programming paradigms. Functions may fit easily on values interior containers, such as Option, List, Future,
3 min read
Trait Linearization in Scala Scala Linearization is a deterministic process which comes into play when an object of a class is created which is defined using inheritance of different traits and classes. linearization helps to resolve the diamond problem which occurs when a class or trait inherits a same property from 2 differen
5 min read
Scala Constructs Some of the basic Scala constructs are expressions, blocks, classes, objects, functions, methods, traits, Main methods, fields, and closures. 1. Scala Expression: A computable statement in Scala is known as expression. For example, the following is an expression: 3 + 4. To print the output of an exp
5 min read