第16课:Scala implicits编程彻底实战及Spark源码鉴赏

来源:互联网 发布:volatile 修饰数组 编辑:程序博客网 时间:2024/06/05 08:21

一、隐式转换介绍

(1)      包括隐式参数、隐式对象、隐式类

(2)      scala独有的。

(3)      当调用对象中不存在的方法,系统会扫描上下文和伴对象看是否有implicit方法,如果有隐式方法则调用隐式方法,隐式方法传入原生对象返回包含扩展方法的对象。

 (4)原类型和伴生对象都找不到的隐式值,会找手动导入的implicit

  Import spark.implicit._

二、spark源码中的使用场景

RDD object中implicit使用。RDD是抽象类处理的是Record,不能处理具体如key value逻辑.

 

objectRDD {

 
// The following implicit functions were in SparkContextbefore 1.3 and users had to
  // `import SparkContext._` to enablethem. Now we move them here to make the compiler find
  // them automatically. However, westill keep the old functions in SparkContext for backward
  // compatibility and forward to thefollowing functions directly.

 
implicit def rddToPairRDDFunctions[K,V](rdd: RDD[(K,V)])
    (
implicit kt:ClassTag[K],vt:ClassTag[V],ord:Ordering[K] =null):PairRDDFunctions[K,V] = {
   
new PairRDDFunctions(rdd)
  }

源码说明:RDD中不具有reduceByKey方法。通过rddToPairRDDFunctins这个隐式方法使RDD带有PairRDDFunctions中的方法:reduceByKey。


三、示例 

package com.ztad.scala.basic


import com.sun.xml.internal.ws.wsdl.writer.document.Import
/**
 * 蘑菇云第16课 
 */
class Man(val name:String){
   def eat()={
     println(name+" eat!")
   }
}
object Man{
  implicit def  doDecode(man:Man):SuperMan={
      return new SuperMan(man)
  }
}


object extManObj{
  implicit def  domkm(man:Man):ExtMan={
      return new ExtMan(man)
  }
}


class SuperMan(man:Man){
   def run(){
     println(man.name+" running!")
   }
}


class ExtMan(man:Man){
   def makeMoney(){
     println(man.name+" make moneyt!")
   }
}


object M16implict {
  def main(args:Array[String]):Unit={
    val man=new Man("li")
    man.run()
    import com.ztad.scala.basic.extManObj._
    man.makeMoney()
    implicit val content="kk"
    talk("li")("all")
    talk("li")
  }
  def talk(name:String)(implicit content:String){
    println(name+" "+content)
  }
  
}

0 0
原创粉丝点击