标签:bsp asp read str second 定义 template gad 转换
/** * Scala中上下文界定内幕中的隐式参数与隐式参数的实战详解及其在Spark中的应用源码解析 */ //[T: Ordering] 这种写法 说明存在一个隐式类型Ordering[T] class Pair_Implicits[T: Ordering](val first: T, val second: 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 = /** * 在Predef中定义了implicitly一个方法 可以简化上面的写法 * @inline def implicitly[T](implicit e: T) = e * 不使用implicit的隐形类型转换 */ if (implicitly[Ordering[T]].compare(first, second) > 0) first else second } class Pair_Implicitly_Ordereded[T: Ordering](val first: T, val second: T) { def bigger = { import Ordered._ if (first > second) first else second } } object Context_Bounds_Internals { def main(args: Array[String]): Unit = { println(new Pair_Implicits(7, 9).bigger) println(new Pair_Implicitly(7, 9).bigger) println(new Pair_Implicitly_Ordereded(7, 9).bigger) } }
import java.io.File import scala.io.Source object Context_Helper{ implicit class FileEnhancer(file : File){ def read = Source.fromFile(file.getPath).mkString } implicit class Op(x:Int){ def addSAP(second: Int) = x + second } } object Implicits_Class { def main(args: Array[String]){ import Context_Helper._ println(1.addSAP(2)) println(new File("F:\\1.txt").read) } }
abstract class Template[T] { def add(x: T, y: T): T } abstract class SubTemplate[T] extends Template[T] { def unit: T } //执行过程检查当前作用是否有 implicit object 限定的 类型为 SubTemplate 的对象, // 如有,则选取此对象。 object Implicits_Object { def main(args: Array[String]) { implicit object StringAdd extends SubTemplate[String] { override def add(x: String, y: String) = x concat y override def unit: String = "" } implicit object IntAdd extends SubTemplate[Int] { override def add(x: Int, y: Int) = x + y override def unit: Int = 0 } //含有隐式参数,m是隐式对象部分 def sum[T](xs: List[T])(implicit m: SubTemplate[T]): T = {println(xs,m) if (xs.isEmpty) m.unit else m.add(xs.head, sum(xs.tail))} println(sum(List(1, 2, 3, 4, 5))) println(sum(List("Scala", "Spark", "Kafka"))) } }
运行结果:
(List(1, 2, 3, 4, 5),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
(List(2, 3, 4, 5),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
(List(3, 4, 5),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
(List(4, 5),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
(List(5),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
(List(),com.wanji.scala.implicits.Implicits_Object$IntAdd$2$@6b143ee9)
15
(List(Scala, Spark, Kafka),com.wanji.scala.implicits.Implicits_Object$StringAdd$2$@1936f0f5)
(List(Spark, Kafka),com.wanji.scala.implicits.Implicits_Object$StringAdd$2$@1936f0f5)
(List(Kafka),com.wanji.scala.implicits.Implicits_Object$StringAdd$2$@1936f0f5)
(List(),com.wanji.scala.implicits.Implicits_Object$StringAdd$2$@1936f0f5)
ScalaSparkKafka
标签:bsp asp read str second 定义 template gad 转换
原文地址:https://www.cnblogs.com/sunrunzhi/p/9729638.html