scala context-abstractions

Conversion is changing the type of data to another type. Scala does some of these conversions for us. For instance,

val a: Int = 'A'
 
// a is 65

So, integer value for character A is assigned to variable a.

However, Scala doesn’t do most of other conversions. We have to defined Conversion instances for that.

A conversion instance is an instance of scala.Conversion class.

case class Person(name: String)
 
given Conversion[String, Person] with
    def apply(s: String): Person = Person(s)

A Conversion instance for String to Person is defined. Whenever a String is assigned to a Person, Scala does that conversion as it has the implicit instance for this.

val p: Person = "Nitin"
 
// p is Person("Nitin")

How it works?

It works in following steps

  1. Scala finds the matching conversion instance
  2. Gives the source type as an argument to apply method of the instance
  3. apply method returns the target data type.
val p: Person = "Nitin"
 
// it is like
 
summon[Conversion[String, Person]].apply("Nitin")