Getting started with Scala to mastery--19th section implicit conversion and implicit parameters (ii)

Source: Internet
Author: User

Rocking Teen Dream
Companion video address: HTTP://WWW.XUETUWUYOU.COM/COURSE/12

The main contents of this section
    1. Implicit conversions in implicit parameters
    2. Overview of implicit parameter usage in functions
    3. An implicit conversion problem carding
1. Implicit conversions in implicit parameters

In the previous talk, we mentioned that if there is an implicit parameter in the function, if the function is not given the corresponding parameter, then the compiler will automatically help us to search for the corresponding implicit value, and the implicit value as a function parameter, which does not involve implicit conversion, this section will show how to use implicit parameters for implicit conversion, The following code is given a normal comparison function:

object ImplicitParameter extends App {//下面的代码不能编译通过//这里面泛型T没有具体指定,它不能直接使用//<符号进行比较  def compare[T](first:T,second:T)={    if (first < second)       first     else       second  }}

The above code, if it is to be compiled, can be defined by the former type variable and the view definition to specify an upper bound of ordered[t], for example:

object ImplicitParameter extends App {  //指定T的上界为Ordered[T],所有混入了特质Ordered  //的类都可以直接的使用<比较符号进行比较  def compare[T<:Ordered[T]](first:T,second:T)={    if (first < second)       first     else       second  }}

This is a solution, and we have a solution that is implemented by implicit conversion of implicit parameters, the code is as follows:

object ImplicitParameter extends App {//下面代码中的(implicit order:T=>Ordered[T])//给函数compare指定了一个隐式参数//该隐式参数是一个隐式转换  def compare[T](first:T,second:T)(implicit order:T=>Ordered[T])={    if (first > second)       first     else       second  }  println(compare("A","B"))}
2. Overview of implicit parameter usage in functions

Point 1: When defining a function, if the function is not implicit, the keyword will be used for all parameters, for example:

//implicit关键字在下面的函数中只能出现一次//它作用于两个参数x,y,也即x,y都是隐式参数def sum(implicit x: Int, y: Int) = x + y//下面的函数不合法,函数如果没有柯里化,不能期望//implicit关键字会作用于其中一个参数//def sum(x: Int, implicit y: Int) = x + y//def sum(implicit x: Int, implicit y: Int) = x + y

In addition, it is worth noting that, def maxFunc(implicit x: Int, y: Int) = x + y when used, you can only specify an implicit value, that is, the specified implicit value corresponds to the parameters in the function (here is x, y), the code is as follows:

def sum(implicit x: Int, y: Int) = x + y//只能指定一个隐式值//例如下面下定义的x会自动对应maxFunc中的//参数x,y即x=3,y=3,从而得到的结果是6implicit val x:Int=3//不能定义两个隐式值//implicit val y:Int=4  println(sum)

Point 2: To use implicit only for a function parameter, you need to curry the function, such as:

Int)(implicit y:Int)=x+y

It is important to note that the following two functions with implicit arguments are also illegal

Int)(implicit y:Int)(d:IntInt)(implicit y:Int)(implicit d:Int)=x+y+d

Point 3: Anonymous functions cannot use implicit parameters, for example:

sum2=(implicit x:Int)=>x+1

Point 4: If a function has an implicit argument, its partial function cannot be used, for example:

sum(x: Int)(implicit y:Int)=x+y //不能定义sum的偏函数,因为它带有隐式参数 //could not find implicit value for //parameter y: Int//not enough arguments for method sum:// (implicit y: Int)Int. Unspecified value parameter y. def sum2=sum _
3. Implicit conversion problem Grooming

1 Multiple implicit conversion issues
In the previous talk we mentioned that implicit conversions do not occur multiple times from the source type to the target type, that is, the conversion of the source type to the destination type will only occur once

class  richfile   (Val file:file)  { def  read=source.fromfile (file). Getlines (). Mkstring}//richfileanother class, which defines the Read2 method  class  richfileanother   (val file:richfile)  {  def} //the implicit conversion does not occur more than once, the following statement will be error-  //cannot expect file to Richfile to occur, then rifchfile to  // The conversion of richfileanthoer  val  f=new  File ( Span class= "hljs-string" > "File.log" ). Read2 println (f)  

Note that this refers to the conversion of the source type to the target type only once, not to say that there are no multiple implicit conversions, and that there may be multiple implicit conversions during a generic method call, such as:

 class ClassA {  Override defToString () ="This is Class A"} class ClassB {  Override defToString () ="This is Class B"} class ClassC {  Override defToString () ="This is ClassC"  defPRINTC (C:CLASSC) = println (c)} class CLASSD  Object implicitwhole extends App {ImplicitdefConsumer (B:CLASSB) = {println ("ecommerce")NewClassC} implicitdefD2C (D:CLASSD) = {println ("D2C")NewClassC}//The code below will be implicitly converted two times  //Because there is no Printc method in CLASSD  //Because it will be implicitly converted to CLASSC (this is the first time, D2C)  //Then call the Printc method  //But the Printc method only accepts parameters of type CLASSC  ///However the parameter type passed in is CLASSB  //Type mismatch, resulting in an implicit swap (this is the second time, consumer-to-consumer)  ///Thus finally implementing the method invocation  NewCLASSD (). PRINTC (NewClassB)}

There is also a case where multiple implicit conversions can occur, and if an implicit argument is defined for a function, multiple implicit conversions may occur during the actual execution, as follows:

 Object Main extends App {   class printops() {    defPrint (implicit i:int) = println (i); } implicitdefStr2printops (s:string) = {println ("Str2printops")NewPrintops} implicitdefStr2Int (implicit s:string): Int = {println ("Str2Int") Integer.parseint (s)} implicitdefgetString = {println ("GetString")"123"}//The following code will occur three times implicit conversions  //First the compiler discovers that the string type is not the Print method  //Try an implicit conversion, using the Str2printops method to set the string  //Convert to Printops (first time)  //Then call the Print method, but the print method accepts an implicit argument of an integral type  //The compiler searches for an implicit value, but the program does not have a given, at which point  //The compiler will attempt to invoke the Str2Int method for implicit conversion, but the method  ///accept a implicit string type argument, the compiler will try to  //Find a corresponding implicit value, which is not at this time, so the compiler tries to call  the//getstring method corresponds to the string (this is the second implicit conversion,  //Get a string, the process from scratch)  after you get the string, call the Str2Int method to type string  //Convert to int type (this is the third implicit conversion)  "a". Print}

The above example comes from: The Patriot Blog, thanks to the author's selfless dedication

2 Do not use implicit conversion problems

As can be seen from the above code, the implicit conversion function is very powerful, but also brings the complexity of the problem, in a program if a large number of implicit conversion, especially when it involves multiple implicit conversion, the code will become more difficult to understand, whether or not to use implicit conversion it? Here are some of my own development practices in the summary, for your reference:
1 even if you can easily navigate the implicit conversion in the Scala language, you can use it without the implicit conversion.
2 If it is to be used, it is necessary to convince yourself of the rationality of doing so when it involves multiple implicit conversions.
3 If you're just showing off your Scala language skills, use it boldly.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Getting started with Scala to mastery--19th section implicit conversion and implicit parameters (ii)

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: 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.