Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Scala初探

1,537 views

Published on

a brief introduction to scala in my team,which is mainly in Java

Published in: Technology
  • 谢谢你的ppt,很不错~
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Scala初探

  1. 1. Scala 初探—— 于Scala,FP,Actor的故事——王简之(星彦)支付宝
  2. 2. Scala是Java的语法糖不是JVM的替代者java实现不了的scala也无法实现
  3. 3. What is Scala纯面向对象,classtraitmixin Martin Odersky函数式first class,lambda,closure,curry,lazy,tailrecursive optActor, pattern-matchJvm bytecode(1.5 compatible)强类型,静态语言,
  4. 4. Scala现状主流版本2.9.x (2.9.2 in stable,2.9.1)未来版本2.10.x (2.10.0 milestone 2)
  5. 5. Scala现状(Cont)sbt:项目管理工具akka:更加成熟的actor实现play framework 2:MVC框架scala+akka+play = TypeSafe
  6. 6. Scala现状(cont)Spark(Hadoop)Kafka(MQ,Linkedin)
  7. 7. 基本语法var a:Int = 1 / val a:Int = 1def func(a:Int):Double = { a * 2}var f2 = func _var f = (a:Int) => a*2
  8. 8. trait Animal {def sle ep():Animal }
  9. 9. CanWa keUp { trait Animal { trait def wake up = {def sle ep():Animal d up”) tln(“I’m wake } prin }}
  10. 10. CanWa keUp { trait Animal { trait def wake up = { def sle ep():Animal d up”) tln(“I’m wake } prin }}class Person extends Animal with CanWakeUp{def sleep():Animal = { var time = 0 loopWhile(time< 7*3600) { time += 1 if(time % 3600 == 0) wakeup() }}
  11. 11. def buildStream(start:Int,f:Function1[Int,Int]):Stream[Int] = { Steam.cons(start,buildStream(f(start),f)) }
  12. 12. def buildStream(start:Int,f:Function1[Int,Int]):Stream[Int] = { Steam.cons(start,buildStream(f(start),f)) } val addInt = (in:Int) => in + 1
  13. 13. def buildStream(start:Int,f:Function1[Int,Int]):Stream[Int] = { Steam.cons(start,buildStream(f(start),f)) } val addInt = (in:Int) => in + 1 val stream = buildStream(0,addInt)stream.take(7*3600).filter(k => k % 3600 == 0).foreach(_ => wakeup())
  14. 14. def buildStream(start:Int,f:Function1[Int,Int]):Stream[Int] = { Steam.cons(start,buildStream(f(start),f)) } val addInt = (in:Int) => in + 1 val stream = buildStream(0,addInt)stream.take(7*3600).filter(k => k % 3600 == 0).foreach(_ => wakeup()) //在2个小时到5个小时之间 stream.drop(2*3600).take(3*3600).filter(k => k % 3600 == 0).foreach(t => wakeup())
  15. 15. 函数式2*3+4+5*7 = 2.multiply(3).add(4).add(5.multiply(7))= multiply(2,3).add(4).add(multiply(5,7)) val temp1 = 2 * 3 val temp2 = temp1 + 4 val temp3 = 5*7 return temp2 + temp3
  16. 16. 函数式函数是“一等公民”:函数可以赋值,可以作为参数,可以作为返回值等List(1,2,3,4).foreach(print)只用函数(function),不用语句(statement)没有side effect,函数保持独立,等幂性
  17. 17. 高阶函数与currydef sum(a:Int,b:Int,c:Int) = a + b + cval addWith1 = sum(1,_:Int,_:Int) addWith1(2,4) / 7 /val addWith1And2 = addWith1(2,_:Int) addWith1And2(3) / 6 /
  18. 18. val list:List[DO] = DAO.getAll()var map:Map[Int,DO] = Map()for(val Do <- list) map += (Do.getId -> DO)
  19. 19. val list:List[DO] = DAO.getAll()var map:Map[Int,DO] = Map()for(val Do <- list) map += (Do.getId -> DO) val map = DAO.getAll().foldLeft(HashMap[Int,DO] ())((acc,ele) => acc += (ele.getId -> ele)
  20. 20. int sum = 0 List(1,2,3,4) => Sum => 10for(int i = 0 ;i < list.size();i++){ sum += list.get(i)}
  21. 21. int sum = 0 List(1,2,3,4) => Sum => 10for(int i = 0 ;i < list.size();i++){ sum += list.get(i)} => acc + ele) ft(0)((acc,ele) list.foldLe
  22. 22. int sum = 0 List(1,2,3,4) => Sum => 10for(int i = 0 ;i < list.size();i++){ sum += list.get(i)} => acc + ele) ft(0)((acc,ele) list.foldLe list.reduceLeft((acc,ele) => acc+ ele)
  23. 23. int sum = 0 List(1,2,3,4) => Sum => 10for(int i = 0 ;i < list.size();i++){ sum += list.get(i)} => acc + ele) ft(0)((acc,ele) list.foldLe list.reduceLeft((acc,ele) => acc+ ele) list.reduceLeft( _ + _)
  24. 24. implicit赋予静态语言的动态性,隐式类型转换在定义的执行上下文中寻找implicit实现有很多坑
  25. 25. implicit cont(1)1.需求:给定一个日期,获取该日的起始和终止时间def getStartAndEndOfDay(date:Date):(Date,Date) = {} val today = new Date() getStartAndEndOfDay(today)._1
  26. 26. implicit cont(1) 1.需求:给定一个日期,获取该日的起始和终止时间def getStartAndEndOfDay(date:Date):(Date,Date) = {} val today = new Date() getStartAndEndOfDay(today)._1{ implicit def getStartAndEndOfDay(date:Date): (Date,Date) = {} val today = new Date() today._1}
  27. 27. implicit 隐式类型转换 List models = DAO.quer yBy() / ava List /jmodels.reduceLeft(_ + _) / anot do this /c
  28. 28. implicit 隐式类型转换 List models = DAO.quer yBy() / ava List /jmodels.reduceLeft(_ + _) / anot do this /c List models = DAO.quer yBy() / ava List /j import scala.collection.JavaConversions._ models.reduceLeft(_ + _) / an do /c
  29. 29. implicit const(2)隐式参数,在执行的上下文中寻找同类型的参数def add(x:Int)(implicit y:Int) = x + y implicit val n:Int = 100 add(5) / 105 /
  30. 30. tail recursive opt //尾递归//递归def sum(i:Int):Int = { @tailrec if(i<=0) def sum(i:Int,sum:Int) = { return i if(i<=0) else return sum return u +sum(i-1) else } return sum(i-1,sum+i) }
  31. 31. Pattern Match(53362,”Jianzhi Wang”,1986) match {case _,”Jianzhi Wang”,_ => / /mecase _,x:String,born:Int if(born >=1980 && born <1990)=> //someone else 80’
  32. 32. ActorSTM:Clojure/Scala (Software TransactionalMemory)Actor:Scala/ErlangChannel Communication:Golang
  33. 33. class CrewQueryActor extends Actor { def act() = { loop{ react{ case (x:String,”name”) =>reply(queryForName(x)) case (x:String,”depart”) => reply(queryForDepart(x)) } }}
  34. 34. val crewQueryActor = new CrewQueryActor().start() //asyn crewQueryActor ! (“jianzhi wang”,”name”); react { case x:Employ => ..... } //sync crewQueryActor !? (“jianzhi wang”,”name”) match{ case x:Emply => .... }val f:Future = crewQueryActor !! (“jianzhi wang”,name)//do somethingf.get match{ case x:Employ => ... }
  35. 35. case “query” => crewQueryActor ! (“jianzhi wang”,”name”);case x:Employ => ...
  36. 36. Actor模式系统调用变成纯粹的消息(协议)调用,解耦 保调用方和依赖方只依赖消息体本身有利于模块化和移植,任意以actor都可以部署到其他机器,变成 remote Actor,代码不需要做很大的变动每个actor就是一个生态圈,当任务易于被切分时Actor提供了简便的执行方法
  37. 37. Actor模式丧失了编译器的类型检查,模式匹配可能不成功,如果是同步调用则容易阻塞发送方随着Actor数量的增多,相互的调用 系可能会形成一个 杂的图队列对CPU cache不友好,不利于低响应系统
  38. 38. Actor不能解决资源争夺,存款取款(消息的投递无法保证先后)Actor阻塞之后的
  39. 39. 那些年我犯过的错误
  40. 40. 那些年我犯过的错误 1.Actor没有Match导致阻塞
  41. 41. 那些年我犯过的错误 1.Actor没有Match导致阻塞class ActReceive { def act() = { loop{ react{ case x:Int => reply(“works”) }}}}
  42. 42. 那些年我犯过的错误 1.Actor没有Match导致阻塞class ActReceive { def act() = { loop{ react{ case x:Int => reply(“works”) exten ds Actor{ }}}} Clas sInvokerActor def act(){ lo o p{ eceive !? “Are y o u OK” match { actR case “works” => / / doSo methine } / /never run here
  43. 43. 2.此List非彼List
  44. 44. 2.此List非彼ListXXXXTableDAO.queryAll() match { case x:List[Model] => { } case _ => {} }
  45. 45. 2.此List非彼ListXXXXTableDAO.queryAll() match { case x:List[Model] => { } case _ => {} } import scala.collection.JavaConversions XXXXTableDAO.queryAll() match { case x:List[Model] => { } case _ => {} }
  46. 46. 3.Memory Leak var actReceive = new ActReceive().start()def test{ loop{ actReceive ! “abcabc” }}
  47. 47. 3.Memory Leakclass ActReceive { def act() = { loop{ react{ case x:Int => reply(“works”) }}}} var actReceive = new ActReceive().start() def test{ loop{ actReceive ! “abcabc” } }
  48. 48. Scala缺陷不同版本二进制不兼容编译时间长学习曲线 峭,函数式比较深奥

×