scala光速入门第四天

总结笔记

1.scala模式匹配

Scala的模式匹配,与Java的switch case的区别:不仅可以匹配值,可以匹配类型;可以匹配数组的集合

实例:def bigData(data: String) {
    data match {
      case "spark"              => println("saprk")
      case "hadoop"             => println("hadoop")
      case _ if data == "flink" => println("flink")
      case _                    => println("something else")
    }
  }

2.类型体系
泛型类、泛型函数、类型界定(upperBound)、视图界定(View Bounds)、协变和逆变

def exception(e: Exception) {
    e match {
      case fileException: FileNotFoundException => println("FileNotFoundException :" + fileException)
      case _: Exception                         => println("big Exceotion")
    }
  }

作业:阅读Spark源码 RDD、HadoopRDD、SparkContext、Master、Worker的源码,并分析里面使用的所有的模式匹配和类型参数的内容

  1.    * 定义了newAPIHadoopFile方法,它有三个类型K,V,F 
  2.    * 类型K,V,F使用限定,是这三个类型都是NewInputFormat[K, V]的子类型; 
  3.   def newAPIHadoopFile[K, V, F <: NewInputFormat[K, V]]  
  4.       (path: String)  
  5.       (implicit km: ClassTag[K], vm: ClassTag[V], fm: ClassTag[F]): RDD[(K, V)] = withScope {  
  6.     newAPIHadoopFile(  
  7.       path,  
  8.       fm.runtimeClass.asInstanceOf[Class[F]],  
  9.       km.runtimeClass.asInstanceOf[Class[K]],  
  10.       vm.runtimeClass.asInstanceOf[Class[V]])  
  11.   }  
  12.  /* 
  13.    * 类型参数的泛型:视图界定(View Bounds) 
  14.    * 定义了rddToSequenceFileRDDFunctions方法,它有两个类型K,V,它们是Writable类型或者被隐式转换为Writable类型 
  15.    * 带一个参数rdd,它是带有(K, V)类型的RDD 
  16.    * 方法返回一个带有类型(K, V)的SequenceFileRDDFunctions 
  17.    * ClassTag是具有丰富的上下文信息,运行时推断具体的类型。 
  18.    * implicit隐式转化 
  19.    */      
  20.   def rddToSequenceFileRDDFunctions[K <% Writable: ClassTag, V <% Writable: ClassTag](  
  21.       rdd: RDD[(K, V)]): SequenceFileRDDFunctions[K, V] = {  
  22.     val kf = implicitly[K => Writable]  
  23.     val vf = implicitly[V => Writable]  
  24.     // Set the Writable class to null and `SequenceFileRDDFunctions` will use Reflection to get it  
  25.     implicit val keyWritableFactory = new WritableFactory[K](_ => null, kf)  
  26.     implicit val valueWritableFactory = new WritableFactory[V](_ => null, vf)  
  27.     RDD.rddToSequenceFileRDDFunctions(rdd)  
  28.   }  
  29.  /* 
  30.    * 类型参数的泛型:上下文界定 
  31.    * 定义了rddToSequenceFileRDDFunctions方法,它有两个类型K,V,它们是Writable类型或者被隐式转换为Writable类型 
  32.    * K : Ordering : ClassTag 表示存在一个隐式值Ordering[K],上下文界定 
  33.    * 方法返回一个带有类型[K, V, (K, V)] 的OrderedRDDFunctions 
  34.    * ClassTag是具有丰富的上下文信息,运行时推断具体的类型。 
  35.    */   
  36.   @deprecated("Replaced by implicit functions in the RDD companion object. This is " +  
  37.     "kept here only for backward compatibility.", "1.3.0")  
  38.   def rddToOrderedRDDFunctions[K : Ordering : ClassTag, V: ClassTag](  
  39.       rdd: RDD[(K, V)]): OrderedRDDFunctions[K, V, (K, V)] =  
  40.     RDD.rddToOrderedRDDFunctions(rdd)  
原文地址:https://www.cnblogs.com/qq852667211/p/5101951.html