scala的隐式转换和隐式调用

//隐式转换 /**

  1. Scala的隐式转换,其实最核心的就是定义隐式转换函数,即implicit conversion function。 *
  2. 它不仅能够简化程序设计,也能够使程序具有很强的灵活性定义的隐式转换函数,只要在编写的程序内引入,就会被Scala自动使用。 *
  3. 隐式转换的关键字是implict * 把implict关键字所修饰的函数称为隐式转换函数 *
  4. 隐式转换的命名风格source2Terget source输入的格式Terget想要得到的格式 *
  5. 用户无需手动调用隐士函数,它是有Scala程序自动进行调用。
 package scaladay02.com.aura
object ImplicitConversion {
  def main(args: Array[String]): Unit = {
//定义隐式转换将String类型的参数转为Int类型
    implicit def str2Int(str:String):Int=str.length
    val str:Int="abcdaa"
    println(str)
//将peopel进行隐式转换为int类型
    implicit def person2Int(person:People01):Int=person.getAge
   //在此处是用来隐式调用自动调用定义的隐式转换方法
    val p:Int=new People01()
println(p)
  }
}
class People01{
  //封装属性
  private var name:String=_
  private var age:Int=10
  def setName(n:String)={
    name=n
  }
  def getName()=name
  def setAge(a:Int)= {
    age = a
  }
  def getAge=age
}

scala隐式转换自定义API

package scaladay02.com.aura

import java.io.File

import scala.io.Source

/**使用隐式转换丰富现有API
  * 当现有的API无法满足我们得需求时我们可以用隐式转换定义我们需要的API
  * 也就是用隐式转换来丰富现有的API
  */

object AddAPI {
  def main(args: Array[String]): Unit = {
    class RichFile(file:File){
      //定义文件的读取
      def read={
        Source.fromFile(file).mkString
      }

    }
    //定义隐式转换
  implicit  def file2RichFile(file:File):RichFile=new RichFile(file)
  //创建对象传入文件路径
    val file=new File("data/data.log")
    //自动调用隐式转换
    println(file.read)
  }
}

隐式转换的引用

//隐式转换的引用
/
*隐式转换的引用和普通类的引用也是通过import关键字来完成的

  • 只要将隐式转换函数引入到自己能访问到的作用域就可以自动应用了
  • 如果是在本类定义只要在前面能够扫描到这个隐式转换即可
    /*
package scaladay02.com.aura
import java.io.File
import scaladay02.com.aura.AddAPI._
object Quote {
  def main(args: Array[String]): Unit = {
val file=new File("data/data.log")
 println(file.read)
  }
}

隐式参数

*** 隐式参数

  • 是指在函数或方法中定义一个implicit修饰的参数
  • 此时scala会尝试找到一个指定类型的用implicit修饰的对象
  • 即隐式值并注入参数
  • scala会在两个范围寻找一个是当前作用域可见的val或var
  • 一个是隐式参数的伴生对象内的隐式值
package scaladay02.com.aura
object ImplicitParameters {
  def main(args: Array[String]): Unit = {
    val list = List(6, 3, 6, 2, 63, 552, 2, 2)
    list.sorted.foreach(println)
  }

  def implicitPar: Unit ={
    //定义集合
    val list = List (new People02 ("王敏", 12),
    new People02 ("王明", 10),
    new People02 ("张琴", 20),
    new People02 ("莉莉", 22) )
//定义隐式参数
    implicit val order = new Ordering[People02] () {
    override def compare (x: People02, y: People02): Int = {
  //定义隐式参数的比较条件
    y.age.compareTo (x.age)
  }

  }
    //相同类型的隐式转换参数,在可访问的作用域内不可重复,否则冲突
    /*implicit val order2 = new Ordering[Person]() {
        override def compare(x: Person, y: Person) = {
            y.name.compareTo(x.name)
        }
    }*/
list.sorted.foreach(println)
  }

}

//方法的定义
class People02{

  var name:String=_
   var age:Int=_
   def this(name:String,age:Int){
     this()
     this.age=age
     this.name=name
   }
}

猜你喜欢

转载自blog.csdn.net/weixin_44701192/article/details/92109007
今日推荐