ITPub博客

首页 > 应用开发 > Java > Scala隐式转换与隐式参数

Scala隐式转换与隐式参数

原创 Java 作者:541732025 时间:2016-02-24 20:00:52 0 删除 编辑
我们有时需要类A具有类B的方法,可以自定义一个隐式转换,将类A转换为类B,在引入这个隐式转换的作用域,使用类A就相当于使用了类B,
这样就达到了增强类A功能的目的
。类似于装饰模式。

点击(此处)折叠或打开

  1. class RichFile(val file:File){
  2.    def read = Source.fromFile(file.getPath()).mkString
  3. }
  4.  
  5. object Context{
  6.     implicit def file2RichFile(file:File)= new RichFile(file) //File -> RichFile,必须有implicit关键字
  7. }

  8. object Hello_Implicit_Conversions {

  9.   def main(args: Array[String]) {
  10.         import Context.file2RichFile //在当前作用域引入隐式转换
  11.      println(new File("D:\\hello.txt").read)  //File本身是没有read方法的,需要隐式转换为自定义的RichFile
  12.   }
  13. }

隐式参数,最直观的是,参数前面有implicit关键字,编译器会在作用域范围内查找谁是implict类型的值,如果有,则作为缺省值。

点击(此处)折叠或打开

  1. object Context_Implicits{
  2.     implicit val default:String = "Flink" //存在一个隐式值
  3. }
  4.  
  5. object Param{
  6.    def print(content:String)(implicit language:String){
  7.       println(language+":"+content)
  8.    }
  9. }
  10. object Implicit_Parameters {

  11.   def main(args: Array[String]) {
  12.     Param.print("Spark")("Scala")
  13.      
  14.     import Context_Implicits._ //从作用域范围内或者Object伴生对象中查找隐式参数
  15.     Param.print("Hadoop") //使用隐式参数
  16.   }
  17. }

隐式参数下的隐式转换

object Implicit_Conversions_with_Implicit_Parameters {
  def main(args: Array[String]) {
    def bigger[T](a: T, b: T)(implicit ordered: T => Ordered[T]) //将匿名函数赋值给ordered变量,该隐式参数将T类型转换为Ordered[T]类型
        = if (a > b) a else b //Ordered实现了<, >等
    println(bigger(4,3))
    println(bigger(4.2,3))
    println(bigger("Spark","Hadoop"))
  }
}

上下文界定中的隐式参数
class Pair_Implicits[T: Ordering](val first: T, val second: T){ //Ordering是泛型,上下文界定说明,只要存在T:Ordering ,就会存在一个隐式值Ordering[T]
  def bigger(implicit ordered: Ordering[T]) =
    if (ordered.compare(first, second) > 0) first else second
}
class Pair_Implicitly[T: Ordering](val first: T, val second: T){
    def bigger =if (implicitly[Ordering[T]].compare(first, second) > 0)  //implicitly提取出运行时上下文界定的实例
            first else second
}
class Pair_Implicitly_Odereded[T: Ordering](val first: T, val second: T){
    def bigger ={
      import Ordered._
      if (first > second) first else second //将Ordering[T]转换为Ordered[T],可以直接使用>
    }    
}

object Context_Bounds_Internals {
  def main(args: Array[String]){
    println(new Pair_Implicits(7, 9).bigger)
    println(new Pair_Implicitly(7, 9).bigger)
    println(new Pair_Implicitly_Odereded(7, 9).bigger)
  }
}

隐式类:对类的功能增强

点击(此处)折叠或打开

  1. object Context_Helper{
  2.     implicit class FileEnhancer(file : File){
  3.         def read = Source.fromFile(file.getPath).mkString
  4.     }
  5.     implicit class Op(x:Int){
  6.          def addSAP(second: Int) = x + second
  7.     }
  8. }
  9. object Implicits_Class {
  10.   def main(args: Array[String]){
  11.     import Context_Helper._
  12.     println(1.addSAP(2))
  13.     println(new File("E:\\Test.txt").read)
  14.     
  15.   }
  16. }

隐式对象

点击(此处)折叠或打开

  1. abstract class Template[T] {
  2.       def add(x: T, y: T): T
  3.     }
  4. abstract class SubTemplate[T] extends Template[T] {
  5.       def unit: T
  6.     }
  7. object Implicits_Object {

  8.   def main(args: Array[String]) {
  9.      implicit object StringAdd extends SubTemplate[String] {
  10.         override def add(x: String, y: String) = x concat y
  11.         override def unit: String = ""
  12.       }
  13.       implicit object IntAdd extends SubTemplate[Int] {
  14.         override def add(x: Int, y: Int) = x + y
  15.         override def unit: Int = 0
  16.       }
  17.       def sum[T](xs: List[T])(implicit m: SubTemplate[T]): T = //m为隐式对象,根据T的具体类型引入相应的隐式对象
  18.      
  19.       if (xs.isEmpty) m.unit
  20.       else m.add(xs.head, sum(xs.tail)) 

  21.       println(sum(List(1, 2, 3, 4, 5))) //引入IntAdd隐式对象
  22.       println(sum(List("Scala", "Spark", "Kafka"))) //引入StringAdd隐式对象
  23.     
  24.   }

  25. }

隐式转换内幕

点击(此处)折叠或打开

  1. class RicherFile(val file:File){
  2.    def read = Source.fromFile(file.getPath()).mkString
  3. }
  4.  
  5. class File_Implicits( path: String) extends File(path)
  6. object File_Implicits{
  7.     implicit def file2RicherFile(file:File)= new RicherFile(file) //File -> RicherFile
  8. }

  9. object Implicits_Internals {
  10.     def main(args: Array[String]) {

  11.         //因为类可以访问伴生对象里的所有内容,所以这里不需要import
  12.         println(new File_Implicits("E:\\Test.txt").read) //当前作用域没有import隐式参数,尝试从类的伴生对象中查找
  13.     }
  14. }

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/28912557/viewspace-1993997/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Scala的Abstract Types
下一篇: Scala并发编程
请登录后发表评论 登录
全部评论

注册时间:2013-05-23

  • 博文量
    127
  • 访问量
    515714