Scala初探
Upcoming SlideShare
Loading in...5
×
 

Scala初探

on

  • 875 views

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

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

Statistics

Views

Total Views
875
Views on SlideShare
874
Embed Views
1

Actions

Likes
3
Downloads
7
Comments
1

1 Embed 1

http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Apple Keynote

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel

11 of 1

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
  • 谢谢你的ppt,很不错~
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n

Scala初探 Scala初探 Presentation Transcript

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