隐式转换和隐式参数

作用:能够丰富现有类库的功能,对类的方法进行增强

隐式转换函数:以implicit关键字声明并带有单个参数的函数

练习1


RichFile.scala

package day04

import scala.io.Source

class RichFile(val file: String) {

  def read(): String = {
    Source.fromFile(file).mkString("")
  }

}

object RichFile {
  def main(args: Array[String]): Unit = {
    //这个过程是显示的实现了read方法
//    val file = "D:/scala/a.txt"
//    val content: String = new RichFile(file).read()
//    println(content)

    // 隐式的实现read方法(隐式转换)
    import day04.MyPredef.fileToRichFile

    val file = "D:/scala/a.txt"
    val context = file.read()
    println(context)
  }
}

MyProdef.scala

package day04

object MyPredef {
  implicit def fileToRichFile(file: String) = new RichFile(file)

}


练习2

Goddess.scala

package day04

object ImplicitContext {
  implicit object OderingGirl extends Ordering[Girl] {
    override def compare(x: Girl, y: Girl): Int = if (x.faceValue > y.faceValue) 1 else -1
  }
}
class Girl(val name: String, var faceValue: Int){
  override def toString: String = s"name:$name,faceValue:$faceValue"
}

class Goddess[T: Ordering](val v1: T, val v2: T){
  def choose()(implicit ord: Ordering[T]) = if (ord.gt(v1,v2)) v1 else v2
}
object Goddess {
  def main(args: Array[String]): Unit = {

    import ImplicitContext.OderingGirl

    val g1 = new Girl("露露",98)
    val g2 = new Girl("二吊",80)

    val goddess = new Goddess(g1,g2)

    val res = goddess.choose()

    println(res)

  }
}

你可能感兴趣的:(隐式转换和隐式参数)