How does implicit types in scala work with reference to this https://youtu.be/hC4gGCD3vlY?t=263

54 views Asked by At

How does implicit types in scala work with reference to this https://youtu.be/hC4gGCD3vlY?t=263.

Also I did not understand why he mentions that the convertAtoB object is static.

1

There are 1 answers

2
prayagupa On BEST ANSWER

Let's start scala REPL with implicitConversion flag.

$ scala -language:implicitConversions
Welcome to Scala 2.12.3 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_151).
Type in expressions for evaluation. Or try :help.

Say you want to have all the integers wrapped inside Number string as "Number(input)".

Now instead of calling a function each time to convert int to desired type, you can define an implicit method which once sees your input and output as defined in your implicit convertor will do it for you.

example,

scala> object NumberToString { implicit def wrapWithNumber(n: Int): String = s"Number(${n})" }
defined object NumberToString

Note that NumberToString is a singleton class or what static class is in Java world.

scala> import NumberToString._
import NumberToString._

Now if you just define a variable of type Int, there will be no conversion happening because it is already of type Int and compiler is happy.

scala> val asItis = 1000
asItis: Int = 1000

But, if you give it a different type, then compiler will look for implicit methods, and picks up the the one which matches.

scala> val richInt: String = 1000
richInt: String = Number(1000)