In-depth understanding of Scala's implicit conversion system

Source: Internet
Author: User

Summary:By implicit conversion, programmers can deliberately omit some information when writing Scala programs, allowing the compiler to attempt to derive this information automatically during compilation, which can greatly reduce the amount of code, ignoring lengthy, overly detailed code. How to use:1. Mark the method or variable as implicit2. Marks the parameter list of the method as Implicit3. Mark the class as implicit Scala supports two forms of implicit conversions: Implicit values: Used to give a method an implicit view of a parameter: for conversion between types or for a method to be called successfully for a type an implicit parsing mechanismThat is, how the compiler finds missing information, parsing has the following two rules: 1. The implicit entity (implicit method implicit class implicitly Class) is first found under the current code Scope 2. If the first rule finds an implicit entity failure, Continues in the scope of the type of the implicit parameter the scope of the lookup type refers to all associated modules associated with that type, and the type of an implicit entity is the following: (1) If T is defined as T with A with B with C, then A,b,c is the part of T, During the implicit parsing of T, their associated objects are searched (2) If T is a parameterized type, then the type parameter and the part associated with the type parameter are counted as part of T, such as list[string] 's implicit search searches the associated object of list and the associated object of String (3) If T is a singleton type p.t, that is, T is within a P object, then this P object will also be searched (4) If T is a type injected s#t, then s and t will be searched implicit parameters and implicit values:Example 1: Declaring the person method. Its argument is name, type string
scala> def person (implicit name:string) = name   //name is an implicit parameter person: (implicit name:string) String
Call the person method directly
scala>  person for parameter name:string              Person ^
Error! The compiler said unable to find an implicit value for the parameter name to define an implicit value before calling the person method
Scala> implicit val p = "Mobin"   //P is called an implicit value p:string = Mobinscala>= Mobin
Because the P variable is marked as implicit, the compiler searches for implicit values within the scope as missing parameters in cases where the method omits implicit arguments. But if you define an implicit variable in REPL again, you'll get an error when you call the method again.
Scala> implicit val p1 = "Mobin1"= Mobin1scala> person <console>:11= >= string match expected              type stringperson ^
The match failed, so implicit conversions must satisfy unambiguous rules, where declaring implicit parameter types is best used with special or custom data types, do not use int,string these common types, avoid coincidence matching an implicit view implicit conversion to target type: automatic conversion of one type to another type Example 2: Converting an integer to a string type:
Scala> def foo (msg:string) = println (msg) foo: (msg:string) Unit Scala> foo (ten)<console> : one: Error:type mismatch;found:int (ten) Required:stringfoo (ten)^
Obviously cannot be converted successfully, the solution is to define a conversion function for the compiler to automatically convert int to string
Scala> Implicit def inttostring (x:int) = x.tostringinttostring: (x:int) String Scala> foo (10)
An implicit conversion method that does not exist in the calling classExample 3: Enable an object to invoke a method that does not exist in the class by implicit conversion
 class   swingtype{def wantlearned (SW: String)  = println ("Rabbit has learned" +SW)}object swimming{implicit def learningtype (s: Aminaltype)  = new   Swingtype}  Span style= "color: #0000ff;" >class   Aminaltypeobject aminaltype    app{ import   com.mobin.scala.scalaimplicit.swimming._ val Rabbit  = new   Aminaltype rabbit.wantlearned ( "breaststroke") //  breaststroke } 
When the compiler discovers that there is no Wantlearning method on the object when it is called by the Rabbit object, the compiler will look for an implicit view that compiles through it at scope scope, and when the Learningtype method is found, the compiler transforms the object into an object with this method by an implicit conversion. You can then call the Wantlearning method to define the implicit conversion function in the associated object, import the implicit view into the scope when used (such as the Learningtype function in Example 4), and define the implicit conversion function in the Killer object, as well as importing the scope when used. Example 4 Example 4:
classswingtype{def wantlearned (sw:string)= println ("Rabbit has learned" +SW)} Packageswimmingpage{object swimming{Implicit def learningtype (S:aminaltype)=NewSwingtype//to define a conversion function in a package  }}classAminaltypeobject Aminaltypeextendsapp{ImportCom.mobin.scala.scalaimplicit.swimmingpage.swimming._//Import to display when usingVal Rabbit =NewAminaltype rabbit.wantlearned ("Breaststroke")//Breaststroke}
A method such as Inttostring,learningtype is an implicit view, usually a view of int and string, with the following format defined: Implicit def originaltotarget (<argument>: originaltype): TargetTypeIt is usually used in two situations: 1. If the expression does not conform to the type required by the compiler, the compiler will look for an implicit view that meets the requirements at scope scope. In Example 2, when you want to pass an integer type to a method that is required to be a string type parameter, an implicit view of int = string must exist in the scope 2. Given a selection of E.T, if there is no member T in the type of E, the compiler looks for an implicit view that can be applied to type E and the return type contains member T. As Example 3 implicitly-Class: implicit classes are provided after scala2.10, and you can declare classes with implicit, but you need to be aware of the following points:1. There are only a few structural parameters2. Implicit classes must be defined in classes, associated objects, and package objects 3. An implicit class cannot be acase class (The case class will automatically generate the associated object with 2 contradiction in the definition ) 4. Cannot have an identifier with the same name in the scopeExample 5:
object StringUtils {  class Stringimprovement (Val s:string) {   // Implicit class      def increment = s.map (x = = (x +1). ToChar  )  }}object extends   app{  import  com.mobin.scala.implicitpackage.stringutils._  println ( "Mobin". Increment)}
When the compiler calls increment on an Mobin object, it discovers that there is no increment method on the object, and the compiler searches for the implicit entity at scope scope. It is found that a conforming implicit class can be used to convert to the Stringimprovement class with the increment method, and eventually call the increment method.

The time of the implicit conversion:

1. When the type of the parameter in the method is inconsistent with the target type

2. When an object calls a method or member that does not exist in the class, the compiler automatically casts the object implicitly the premise of implicit conversions:1. There is no ambiguity (example 1) 2. Implicit operations cannot be nested (such as Convert1 (Covert2 (x) )) +y 3. The code can be compiled without the use of implicit conversion, the implicit black iron will not be

In-depth understanding of Scala's implicit conversion system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.