Scala隐式转换实战

  • 隐式方法
  • 隐式参数
  • 隐式类
  • 隐式对象

隐式方法

import scala.io.Source
import java.io.File


class RichFile (val file : File){ def read = Source.fromFile(file.getPath) } //导入隐式方法之后file自动会转换至RichFile object Context { implicit def file2RichFile (file : File) = new RichFile(file) } object Hello_implicit { def main(args: Array[String]): Unit = {
    import Context.file2RichFile
    println(new File("E:\\Hello.txt").read)
  }
}

隐式参数

object Context_implicits{
  implicit val default : String = "Java"
}

object Param{
  //声明隐式参数后会在作用域范围内导入默认的参数
  def print(content : String)(implicit language : String){ println(language + " : " + content) } } object implicit_Parameters { def main(args: Array[String]): Unit = {
    Param.print("Spark")("Scala")

    import Context_implicits._
    Param.print("Hadoop")
  }
}

隐式类

object Context_Helper{
  implicit class FileEnhancer(file : File){ def read = Source.fromFile(file.getPath) } implicit class Op (x : Int){ def add (second : Int) = x + second } } object implicit_class { def main(args: Array[String]): Unit = {
    import Context_Helper._
    println(1.add(2))
    println(new File("E:\\Text.txt").read)
  }
}

隐式对象

abstract class Template[T]{ def add(x : T, y : T) : T
}
abstract class SubTemplate[T] extends Template[T]{ def unit : T
}
object implicit_object {
  def main(args: Array[String]): Unit = {
    implicit object StringAdd extends SubTemplate[String]{
      def add(x : String, y : String) : String = x concat y
      def unit : String = ""
    }
    implicit object IntAdd extends SubTemplate[Int]{
      def add(x : Int, y : Int) : Int = x + y
      def unit : Int = 0
    }
    def sum[A](xs : List[A])(implicit m : SubTemplate[A]) : A =
      if (xs.isEmpty) m.unit
      else m.add(xs.head, sum(xs.tail))

    println(sum(List(1, 2, 3)))
    println(sum(List("a", "b", "c")))
  }
}

你可能感兴趣的:(scala)