The implementation of implicit type conversion in Scala

Time:2019-10-17

Implicit transformation in scala is a very powerful language feature, which can play two roles:

I. automatic implicit conversion of some data types

String type cannot be automatically converted to int type, so when a variable or constant of int type is given a value of string type, the compiler will report an error. So, the following statement is wrong.


val x: Int = "100"

If you need to assign a string type integer value to int, for example, use the string.toint method, for example:


val x: Int = "100".toInt

If you want the string to be converted to an integer automatically, you can use implicit conversion. You can define the following functions.


implicit def strToInt(str: String) = str.toInt

When you assign a string to a variable of type int, the string will be automatically converted to int.


scala> val x:Int = "00"
x: Int = 100

If you define a function of adding two numbers at this time,


def add(x: Int, y: Int) = x + y

This effect can be achieved:


scala> add("100", 200)
res1: Int = 300

Implicit transformation has certain rules, and there are two more important ones.

1. According to the book “Scala programming”, the inserted implicit transformation must be in scope in the form of a single identifier, or associated with the source or target type of the transformation. The scala compiler will only consider implicit transformations that are in scope.

In short, before using implicit transformation, you need to use import to reference implicit transformation to the current scope or define implicit transformation in the scope. In addition to implicit conversions being introduced into the current scope, there is another way to use implicit conversions, where the compiler looks for implicit definitions in the source type or the expected companion object.

2. Unambiguous rule: implicit conversion can only be operated when there is no other conversion available. If more than one implicit conversion function is defined for the same source type in the same scope, if multiple implicit conversion functions can match, the compiler will report an error, so please remove unnecessary implicit definitions when using.

II. Implicit parameters

There will be multiple parameter lists in the currification function. When you want to use the default parameter for a parameter list, you can use the implicit parameter function provided by implicit. The method is to add implicit at the beginning of the parameter list that needs to be filled automatically, then define the default parameter value constant that needs to be filled in the definition field, and declare implicit before the constant definition.

Horizon

When defined as


class Container[A <% Int] { def addIt(x: A) = 123 + x }

Indicates that type a must be treated as int. In short, there needs to be a conversion function that can automatically convert type A to int. if there is no such conversion function, you can use implicit definition.

Write a class to test the usage of implicit transformation in scala:

class Fraction(n: Int, d: Int) {
// def den = d
 private val den = d;
//Def num = n class parameter can be defined as either method or field
 private val num = n;

//Define multiplication
 def *(other: Fraction) = Fraction(other.num * this.num, other.den * this.den)
//Override toString
 override def toString() = s"$num / $den" 
}
//Companion object
object Fraction {
//Implicit implicit method name has nothing to do with it. It can be changed at will and called automatically.
 implicit def int2Fraction(n: Int) = Fraction(n, 1)

 def apply(n: Int, d: Int) = {
  new Fraction(n, d)
 }

 def unapply(frac: Fraction) = if (frac.den == 0) None else Some((frac.num, frac.den))
}

object TestFrac extends App{
//3 implicitly calling int2fraction method is converted to a fraction object fraction (3,1)

 val result = 3 * Fraction(4,5)
//Call can also be displayed
 val result2 = Fraction.int2Fraction(5) * Fraction(3,4)
 println(result)
// unapply
 val Fraction(num,den) = result
 println(num,den)

}

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

How to check the package according to the command in CentOS

In our work, we often encounter that we want to use a command machine that is not installed, but we don’t know which package the command is in (source compilation is not covered in this article). Here is a rather stupid method to help us solve this problem. Explain:Blue = command name Light green = […]