Skip to content

Latest commit

 

History

History
87 lines (74 loc) · 2.1 KB

0005.md

File metadata and controls

87 lines (74 loc) · 2.1 KB

第5课:彻底精通Scala隐式转换和并发编程

标签: sparkIMF


##隐式转换

class Person(val name:String)
class Engineer(val name:String,val salary:Double){
    def code = println("Coding....")
}
implicit def person2Enginerr(p:Person):Engineer = {
    new Engineer(p.name,1)
}
	
new Person("a1").code				//result:Coding....
def toCode(p:Person){p.code}
toCode(new Person("Scala"))			//result:Coding....

导入方式:1.通过伴生对象导入 2.手动import导入

##隐式参数

  在上下文中通过隐式参数,在每次运行的上下文实例对象,具体的隐式值,注射入隐式参数中   隐式参数类型的伴生对象中去找隐式值

	class Level(val level:Int)
	def toWorker(name:String)(implicit lvl:Level) = println(name+":"+lvl.level)
	implicit val l = new Level(2)
	toWorker("Spark")	//result:Spark:2
	//---手动导入隐式转换
	object Context_Implicits{ implicit val defaut:String = "FLink" }
	object Param{
		def print(content:String)(implicit language:String): Unit ={
			println(language+ ":"+content)
		}
	}
	object Implicit_Parameter {
	  def main(args: Array[String]) {
		Param.print("Spark")("Scala")
		import Context_Implicits._
		Param.print("Hadoop")
	  }
	}

##并发Actor 异步! 同步!?

	import scala.actors.Actor
	class HiActor extends Actor{
	  def act(){
		while(true){
		  receive{
			case name:String=>println("name:"+name)
		  }
		}
	  }
	}
	val actor = new HiActor()
	actor.start()
	actor ! "Spark"	//发送
	
	class BasicActor extends Actor{
	  def act(){
		while(true){
		  receive{
			case Basic(name,age) => println("Basic Infomation:"+name+" : "+age)
			case worker:Worker => println("Worker Infomation:"+ worker.name+" : "+worker.age)
		  }
		}
	  }
	}
	val b = new BasicActor()
	b.start
	b ! Basic("Scala",13)	//异步发送
	b !? Worker("Spark",7)	//发送并等待回复
	b !! Worker("Spark",7)	//发送并异步等待回复,返回future

Java是共享全局变量的加锁机制

###case class和case object区别: 全局只有一个对象,用case object;如果有很多对象实例,用case class。