scala--implicit conversion and implicit parameters-★★★

Implicit conversions and implicit parameters

  • There are no implicit conversions and implicit parameters in java
  • If you want to use dynamic proxy/AOP and other technologies in Java
  • Overview
    • The implicit conversion and implicit parameter functions provided by Scala are very distinctive, and they are also functions that are not available in programming languages ​​such as Java.
    • You can convert a certain type of object into a specified type or add a new method to a type (you can add new functions to the code without modifying the original code)
    • Later in learning Akka, Spark, Flink, etc., you will see implicit conversions and implicit parameters, which can achieve very powerful and special functions.
  • Implicit conversion
    • The so-called implicit conversion refers to a method with a single parameter declared with the implicit keyword.
    • The defined implicit conversion method will be automatically invoked by Scala as long as it is imported in the written program.
    • According to the signature of the implicit conversion method, Scala will automatically pass it to the implicit conversion method when the object defined by the parameter type received by the implicit conversion method is used in the program, convert it to another type of object, and return it.
  • Implicit parameter
    • The so-called implicit parameter refers to the definition of an implicitly modified parameter in a function or method. At this time, the compiler will try to find a specified type of implicit value modified with implicit and set it to the parameter.
    • Scala will search in two scopes: the implicit variable defined by val or var visible in the current scope, and the implicit value in the companion object of the implicit parameter type.
  • Timing of implicit conversion
    • When the type of the parameter in the method is inconsistent with the target type
    • When an object calls a method or member that does not exist in the class, the compiler will automatically convert the object implicitly
  • Implicit conversion lookup and import
    • (1) Scala will use two implicit conversions by default,
      • One is the implicit conversion function or implicit value in the source type or the companion object of the target type;
      • One is the implicit conversion method or implicit value that can be represented by a unique identifier within the scope of the current program.
    • (2) If it is not in the above two cases,
      • Then you must manually use the import syntax to introduce implicit conversions under a certain package, such as import test._
      • It is generally recommended: Only use import to import implicit conversions where implicit conversions are required, so that the scope of implicit conversions can be narrowed, and unnecessary implicit conversions can be avoided
  • note
    • 1. All the implicit values ​​and implicit methods must be placed in the object.
    • 2. The implicit keyword can only be used to modify methods, variables (parameters) and accompanying objects.
    • 3. The Scala program will automatically import the following packages:
import java.lang._

import scala._

import Predef._

Implicit conversion

  • The implicit conversion in Scala can convert an object into another type according to the implicit conversion, which is convenient to use
  • In future development, we only need to import implicit conversions written by others.
  • Such as:
//spark代码中经常要导入的 
import spark.implicits._ 
//flink代码中经常要导入的
import org.apache.flink.api.scala._
  • Custom implicit conversions and use cases
package cn.hanjiaxiaozhi.implicitdemo
​
import java.io.File
​
import scala.io.Source
​
/**
 * Author hanjiaxiaozhi
 * Date 2020/7/17 16:28
 * Desc 演示Scala中的隐式转换
 */class MyFile(val file:File){
    
    
  //在RichFile中提供一个read方法可以直接读取file中的文件内容并返回字符串
  def read() = {
    
    
    Source.fromFile(file).mkString
  }
}//定义一个object其中提供一个隐式转换方法,可以将File转为MyFile
object File2MyFile{
    
    
  implicit def transform(file:File):MyFile={
    
    
    new MyFile(file)
  }
}object ImplicitDemo1 {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val file = new File("D:\\scala\\data\\1.txt")
    //file.read()//调用不了,因为Java中自带的File中没有read方法
    //现在如果想要让file.read()不抱错,可以执行,那么可以使用Scala中的隐式转换技术
    //将file对象转换为MyFile类型,那么不就可以使用read方法了么!
    //导入上面的隐式转换方法,将file对象转换为MyFile类型
    import File2MyFile.transform//我们以后写的就是这一句,导入别人写好的隐式转换
    //这句类似于导包的语句其实就是导入上面定义好的隐式转换,在编译时期,由编译器自动将file根据隐式转换方法转为MyFile
    val str: String = file.read()
    println(str)
  }
}

Implicit parameter

  • Implicit parameters in Scala can automatically/implicitly pass parameters to methods with implicit parameters by importing parameters
package cn.hanjiaxiaozhi.implicitdemo
​
/**
 * Author hanjiaxiaozhi
 * Date 2020/7/17 16:28
 * Desc 演示Scala中的隐式参数
 */object ImplicitParam {
    
    
  implicit val t1 = ("<<",">>")
  implicit val t2 = ("[","]")
}
​
​
object ImplicitDemo2 {
    
    
  //需求:调用getName方法返回书名并带上书名号
  def getName(name: String)(implicit t:(String,String)): String = {
    
    
    //如果是在这样的话,书名号就写死了,我们希望可以根据不同的参数,进行不同的拼接
    //但是提供参数让调用者传递,调用的时候又很麻烦
    //所以可以使用隐式参数
    t._1 + name + t._2
  }def main(args: Array[String]): Unit = {
    
    
    //这里调用getName的时候传递name即可
    //但是还需要指定一个隐式参数,也就是导包即可
    //import ImplicitParam.t1
    import ImplicitParam.t2
    val name: String = getName("Scala从入门到精通")
    println(name)
  }
}

Guess you like

Origin blog.csdn.net/qq_46893497/article/details/114044024