-3

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.

  • Please refine your question. Add code and state your exact question. It seems you have a question on implicit conversion. Did you have a chance to look at https://docs.scala-lang.org/tour/implicit-conversions.html? You'll find answers on your question about `static`s in Scala by looking at `singleton objects`. – Nader Ghanbari Dec 17 '17 at 02:13

1 Answers1

1

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)
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • Thanks @prayagupd. So implicit types are some templet functions which compiler looks for, when it doesn't find any thing else for a expression to evaluate? – hemshankar sahu Dec 17 '17 at 05:17
  • 1
    There is no such thing as implicit type but implicit conversion from typeA to typeB. So, if the given type or method does not exist then only compiler will look for implicit method. If you have a convertor from `A => A`, it won't make any effect. – prayagupa Dec 17 '17 at 05:40