Scala's implicit conversion __scala

Source: Internet
Author: User
Overview

In short, implicit conversions are: When a Scala compiler does a type match, if the appropriate candidate is not found, implicit conversion provides another way to tell the compiler how to convert the current type to the expected type. The source of this article: http://blog.csdn.net/bluishglc/article/details/50866314 is strictly prohibited in any form of reprint, otherwise will entrust CSDN official maintenance rights and interests.

Implicit conversions have four common usage scenarios: Converting a type to an expected type type enhancement and extension simulates the new syntax type class syntax

Implicit conversions have both new and old methods of defining the old definition method refers to the "Implict def" form, which was written before Scala version 2.10, and after Scala version 2.10, Scala introduced an "implicit class" to replace the old implicit conversion syntax, because the "implicit class" is a more secure way, and the scope of the converted type is more clearly controllable.

We then use examples to understand how these two implicit conversions are written. As mentioned in the preceding article, the most basic use scenario for implicit conversions is to convert a type to the expected type, so our following example demonstrates in the simplest scenario, which implements the implicit conversion of a string variable to type int: "Implict def" Implicit conversions of the form

Package com.github.scala.myimplicit

/**
  * A demo about Scala implicit type conversion.
  * @author Laurence Geng */
object Implicitdefdemo {

    object myimplicittypeconversion {
        implicit def Strtoint (str:string) = Str.toint
    }

    def main (args:array[string]) {
        //compile error!
        Val max = Math.max ("1", 2);
        Import Myimplicittypeconversion.strtoint
        val max = Math.max ("1", 2);
        println (max)
    }
}
implicit conversions in the form of an "implicit class"
Package com.github.scala.myimplicit

/**
  * A demo about Scala implicit type conversion.
  * @author Laurence Geng
  *
/object Implicitclassdemo {

    implicit class Myimplicittypeconversion (Val str: String) {
         def strtoint = Str.toint
    }

    def main (args:array[string]) {
        //compile error!
        Val max = Math.max ("1", 2);
        Import Com.github.scala.myimplicit.implicitdefdemo.myimplicittypeconversion._
        val max = Math.max ("1", 2);
        println (max)
    }
}

There are several limitations to the implicit class:

They must be defined inside of another trait/class/object.

They may only take one non-implicit argument in their constructor.

There May is any method, member or object under scope with the same name as the implicit class.
Note:this means an implicit class cannot is a case class.

Implicit classes are subtly different from the old implicit conversion syntax (implicit def), implicit classes work by: The main constructor of an implicit class can have only one argument (more than two does not complain, but the implicit class is never used by the compiler as an implicit class in implicit conversions), And the type of this parameter is the type of target that will be converted. Semantically This is natural: this implicit conversion class wraps the target type, and all the methods of the implicit class are automatically "appended" to the target type. Application Scenarios convert to expected type

For this use of the scene is not actually very rare, the actual significance is not so big. An example of this scenario is the code for the preceding article. type enhancement and extension

What really makes an implicit conversion shine is "type enhancement." There are a number of examples in this area. Case One: arrayops type enhancement to array

A typical case is Scala's implicit conversion of an array object. As we know, Scala declares the two implicit conversions for the array type through PREDEF: One is an implicit conversion to arrayops and the other is an implicit conversion to wrappedarray. For example, it adds a large number of operations to the array object, which is a typical case of enhancements to a class that is "illuminated" by an implicit conversion. The following is a description of this technical detail in the Scala API documentation:

Two implicit conversions exist in Scala. Predef that are frequently applied to arrays:a conversion to Scala.collection.mutable.ArrayOps (shown on line 4 of the EX Ample above) and a conversion to Scala.collection.mutable.WrappedArray (a subtype of scala.collection.Seq). Both types make available many to the standard operations in the Scala found API. The conversion to Arrayops are temporary, as all operations defined on Arrayops return a Array, while the conversion to Wr Appedarray is permanent as all operations return a wrappedarray.
case Two: the type enhancement of pairrddfunctions to Rdd in Spark

If you look at the RDD in Spark and its subclasses are not Groupbykey, Reducebykey, and join, which are based on key-value tuples, but when you use RDD, these operations are real, Spark is the conversion of a rdd into a pairrddfunctions by an implicit conversion, which occurs as follows:

The implicit conversion from RDD to Pairrddfunctions is declared first in the accompanying object of the RDD:

Then import all of the RDD in the Sparkcontext to make the implicit conversion effective. simulate a new syntax

This is also a very cool application scenario. A typical application scenario is the-> symbol used to create the Key-value tuple in map, which is the product of an implicit conversion. -> is not the syntax of Scala itself, but a method of type Arrowassoc. This type is defined in the package Scala.predef object. Scala.predef is automatically introduced into the current scope, in this object, and defines an implied conversion from type any to ARROWASSOC. Therefore, when 1-> "One" is used, the compiler automatically inserts the conversion from 1 to Arrowasso c.

Type class

A type class is a very flexible design pattern that separates the definition and behavior of a type, making it easy to extend the class behavior. Or if we want to create a feature that spans the type (that is, the functional implementation evolves independently of the type), then such "features" are not suitable and should not evolve on the main type hierarchy, which is the perfect place to use type classes. Because the type class is a more independent syntax, although its implementation requires the use of a type class, in this article we are not going to go into detail here, but in the next article, we will not focus on this. Implicit resolution of search scopes

The rules in this section are somewhat complex, as described in the Scala in Depth, where the search logic at the top is: looking under the current scope. This situation is divided into two cases, one is to display the implicit element of the declaration in the current scope, and the other to import the implicit element through the import. If the first method is not found, the compiler continues to look in the implicit scope of the implicit parameter type.

What's really complicated is what is called an implicit scope of a type. An implicit scope of a type refers to all associated objects of the type associated with the type.

OK, what does that call "type associated with a type". The definition is as follows: If T is so defined: T with A and B with C, then the companion object of A, B, C is the search region of T. If T is a type parameter, then both the parameter type and the underlying type are the search portion of T. For example, for types List[foo],list and Foo are search areas if T is a single instance type P.T, then p and T are search areas if T is type injection p#t, then p and T are search regions. Implicit parameters

Why do we put implicit arguments alone and put them in the end because, implicitly, the implicit arguments are very different from the implicit type conversions we talked about earlier, although it involves keyword implict, but it does something else. A suppressed parameter is somewhat similar to a default parameter, and if a parameter is not supplied when the method is invoked, the compiler will find in the current scope whether a qualified implicit object can be passed in as a parameter, unlike the default parameter, where the value of an implicit parameter can be specified in the context before the method invocation. This is where the implicit parameters are more flexible.

Object Implicitparamdemo {

    object greeter{
        def greet (name:string) (implicit prompt:string) {
            println (" Welcome, "+ Name +". The System is ready. ")
            println (Prompt)
        }

    def main (args:array[string]) {

        implicit Val prompt = ">"

        greeter.greet (" Admin ")
    }

}

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.