SlideShare a Scribd company logo
Scala
                         让Java平台上的编程重现生机

                                           Sparkle




Monday, April 16, 2012
大纲

                     • Scala是什么
                     • 为什么选择Scala
                     • 语法特色,与Java对比
                     • 缺点
                     • 实际使用

Monday, April 16, 2012
Scala是什么



Monday, April 16, 2012
"Which Programming Language would you use *now* on
  top of JVM, except Java?". The answer was surprisingly fast
                   and very clear: - Scala.




                         http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming




Monday, April 16, 2012
I can honestly say if someone had shown me
  theProgramming in Scala book by by Martin Odersky, Lex
  Spoon & Bill Venners back in 2003 I'd probably have never
                       created Groovy.




                          http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html




Monday, April 16, 2012
The Scala research group at EPFL is excited to announce
   that they have won a 5 year European Research Grant of
     over 2.3 million Euros to tackle the "Popular Parallel
                    Programming" challenge.




                                            http://www.scala-lang.org/node/8579




Monday, April 16, 2012
Scala Creator Launches Typesafe to Commercialize Modern
 Application Platform for Multicore and Cloud Computing.

   Typesafe also named to its board of advisors Java creator
    James Gosling and Java concurrency expert Doug Lea.




                         http://www.marketwire.com/press-release/scala-creator-launches-typesafe-commercialize-modern-application-platform-
                                                                                                                   multicore-1513767.htm




Monday, April 16, 2012
TIOBE 2012年4月份

                     • 45名




Monday, April 16, 2012
TIOBE 2012年4月份

                     • 45名
                     • 3月份不在前50名



Monday, April 16, 2012
TIOBE 2012年4月份

                     • 45名
                     • 3月份不在前50名
                     • (Go也不在前50名)


Monday, April 16, 2012
TIOBE 2012年4月份

                     • 45名
                     • 3月份不在前50名
                     • (Go也不在前50名)
                     • (曾经进入前30名)

Monday, April 16, 2012
Scala实现
                     • Play 2.0
                     • Akka(很像Erlang的并发库)
                     • Apollo(下一代ActiveMQ)
                     • Spark(Hadoop竞争者)
                     • Kafka(MQ)
                     • Apache Camel支持Scala DSL
Monday, April 16, 2012
Scala是……
                     • 又一个JVM上的语言(编译型)
                     • 强类型
                     • “动态的”静态语言
                     • 面向对象
                     • 函数式
                     • 并发
Monday, April 16, 2012
Scala不是……
                     • 杀手
                     • 取代JVM
                     • 突破JVM限制
                     • Java实现不了的功能


Monday, April 16, 2012
Scala不是……
                     • 杀手
                     • 取代JVM
                     • 突破JVM限制
                     • Java实现不了的功能
                   你可以认为Scala是大量语法糖的Java

Monday, April 16, 2012
谁在用
                     • Twitter
                     • LinkedIn
                     • FourSquare
                     • Tumblr
                     • Bump
                     • Xerox、Sony、Siemens
Monday, April 16, 2012
为什么选择Scala



Monday, April 16, 2012
Java语法落后了
                         JDK 1.0 (January 23, 1996)
                         JDK 1.1 (February 19, 1997)
                         J2SE 1.2 (December 8, 1998)
                         J2SE 1.3 (May 8, 2000)
                         J2SE 1.4 (February 6, 2002)
                         J2SE 5.0 (September 30, 2004)
                         Java SE 6 (December 11, 2006)
                         Java SE 7 (July 28, 2011)



Monday, April 16, 2012
世间还有这些语言


                     • Erlang Python Ruby Lua C# PHP C++ Go
                     • JRuby Groovy Clojure


Monday, April 16, 2012
为什么选择Scala




Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累




Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化




Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化
                     • 编译成Bytecode——性能保证




Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化
                     • 编译成Bytecode——性能保证
                     • 函数式和OO并存——无痛切换



Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化
                     • 编译成Bytecode——性能保证
                     • 函数式和OO并存——无痛切换
                     • 高级语法——高层抽象


Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化
                     • 编译成Bytecode——性能保证
                     • 函数式和OO并存——无痛切换
                     • 高级语法——高层抽象
                     • 并发——多核的挑战

Monday, April 16, 2012
为什么选择Scala
                     • JVM平台——技术积累
                     • 静态语言——工程化
                     • 编译成Bytecode——性能保证
                     • 函数式和OO并存——无痛切换
                     • 高级语法——高层抽象
                     • 并发——多核的挑战
                     • 其实Scala的学习难度并不高
Monday, April 16, 2012
语法特色,与Java对比



Monday, April 16, 2012
Hello, world!
                   //Java
                   class Test {
                     public static void main(String[] args) {
                       System.out.println("Hello, world!");
                     }
                   }
                   //Scala
                   object Test {
                     def main(args: Array[String]) {
                       println("Hello, world!")
                     }
                   }


Monday, April 16, 2012
Hello, world!

                         //Scala
                         object Test extends Application {
                           println("Hello, world!")
                         }




Monday, April 16, 2012
Java Bean
                  //Java
                  class MyBean {
                    private int x, y;
                    public int getX() { return x; }
                    public void setX(int x) { this.x = x; }
                    public int getY() { return y; }
                    public void setY(int y) { this.y = y; }
                  }
                  //Scala
                  class MyBean(var x: Int, var y: Int) {}




Monday, April 16, 2012
多返回值
                         //Java
                         class MyResult { //xxx }

                         public MyResult getResult() {
                           //xxx
                           return new MyBean(x, y);
                         }

                         MyResult result = getResult();
                         result.getX();




Monday, April 16, 2012
多返回值
                         //Java
                         public Object[] getResult() {
                           //xxx
                           return new Object[]{ x, y };
                         }

                         Object result = getResult();
                         (String)result[0];




Monday, April 16, 2012
多返回值
                         //Scala
                         def getResult = {
                           //xxx
                           (x, y, z)
                         }

                         val (x, _, z) = getResult




Monday, April 16, 2012
模式匹配
                     def matchTest(x: Any) = x match {
                       case 1 => "number one"
                       case y: Int if y > 0 => y + 1
                       case head :: tail => tail
                       case Send(a, _) => a
                       case ("Send", _, b: String) => b
                       case _ => x
                     }
                     //强化版switch
                     //元素提取




Monday, April 16, 2012
模式匹配
                         //Java
                         public boolean equals(Object obj) {
                           if (obj instanceof Point) {
                             Point point = (Point) obj;
                             return x == point.x && y == point.y;
                           } else {
                             return false;
                           }
                         }




Monday, April 16, 2012
模式匹配
  //Scala
  def equals(any: Any) = any match {
    case point: Point => x == point.x && y == point.y
    case _ => false
  }




Monday, April 16, 2012
函数式
                   //Java 当然你不会这样写
                   list.filter(new F<Integer, Boolean>() {
                     public Boolean f(Integer i) {
                       return i % 2 == 0;
                     }
                   });
                   //你可能经常这样写
                   executor.execute(new Runnable() {
                     public void run() {
                       //xxx
                     }
                   });


Monday, April 16, 2012
函数式
                         //Scala 三种写法
                         list.filter(e => e % 2 == 0)

                         list.filter(_ % 2 == 0)

                         val f = (e: Int) => e % 2 == 0
                         list.filter(f)




Monday, April 16, 2012
函数式

                   //Scala 这里有三个循环,不一定是好习惯
                   list.filter(_ % 2 == 0).map(_ / 2).sum




Monday, April 16, 2012
匿名函数
                         //Scala
                         execute {
                           println("check")
                         }

                         def execute(runnable: => Unit) {
                           executor.execute(new Runnable() {
                              def run = runnable
                           })
                         }




Monday, April 16, 2012
匿名函数
  //slf4j
  logger.error("some error: {}, {}, {}", new Object[]
  {x, y, z});

  //Scala msg在访问的时候才会计算!
  def error(msg: => String) {
    if(logger.isErrorEnabled) { logger.error(msg) }
  }
  error("some error: " + x + ", " + y + ", " + z)




Monday, April 16, 2012
open class(ruby)
                         class String
                           def foo
                             "foo"
                           end
                         end
                         puts "".foo # prints "foo"




Monday, April 16, 2012
为什么open class
                     //这不是一个OO行为
                     StringUtils.isBlank("some str")

                     //这才是OO
                     "some str".isBlank

                     //我们需要打开别人的类添加方法,继承并不能满足




Monday, April 16, 2012
为什么open class
          //junit hamcrest
          assertThat(theBiscuit, is(equalTo(myBiscuit)));

          //mockito
          verify(mockedList).add("one");

          //Scala specs2
          "Hello world" must startWith("Hello")
          //DSL !!
          //让第三方框架打开我们的类




Monday, April 16, 2012
隐式转换
                         class MyStr(str: String) {
                           def isBlank = str.trim.length == 0
                         }
                         implicit def myStrW(str: String) =
                           new MyStr(str)

                         println("some str".isBlank)




Monday, April 16, 2012
隐式转换
                         class MyStr(str: String) {
                           def isBlank = str.trim.length == 0
                         }
                         implicit def myStrW(str: String) =
                           new MyStr(str)

                         println("some str".isBlank)

                         println(new MyStr("some str").isBlank)




Monday, April 16, 2012
open class的效果让大家觉得Scala是动态语言,但选择隐
      式转换来实现,正好证明了Scala是静态语言




Monday, April 16, 2012
Traits
               //这是一个经典的Java模式
               interface IAnimal {}

               abstract class Animal implements IAnimal {
                 //公共代码
               }

               class Bird extends Animal implements CanFly {}

               //问题来了,CanFly的公共代码写在哪里



Monday, April 16, 2012
Traits
                         //Scala
                         abstract class Animal { xxx }
                         trait CanFly {
                           def fly {
                             println("fly")
                           }
                         }
                         class Bird extends Animal with CanFly {}




Monday, April 16, 2012
Traits
                         class Fish { xxx }
                         trait CanFly {
                           def fly {
                             println("fly")
                           }
                         }
                         val flyFish = new Fish with CanFly




Monday, April 16, 2012
Traits
                         //按照具体需求装配不同的功能
                         val order = new Order(customer)
                           with MailNotifier
                           with ACL
                           with Versioned
                           with Transactional




Monday, April 16, 2012
Duck Typing
                         class Duck {
                           def quack = "呱...呱..."
                         }
                         def doQuack(d: {def quack: String}) {
                           println(d.quack)
                         }
                         doQuack(new Duck)




Monday, April 16, 2012
Duck Typing
                         class Duck {
                           def quack = "呱...呱..."
                         }
                         type DuckLike = {
                           def quack: String
                         }
                         def doQuack(d: DuckLike) {
                           println(d.quack)
                         }
                         doQuack(new Duck)
                         //是不是有点像Go语言的感觉?



Monday, April 16, 2012
尾递归优化
               def factorial(n: Int): Int = {
                 @tailrec
                 def factorialAcc(acc: Int, n: Int): Int = {
                   if (n <= 1) acc
                   else factorialAcc(n * acc, n - 1)
                 }
                 factorialAcc(1, n)
               }
               //Scala会自动优化成循环,@tailrec只是确保发生优化




Monday, April 16, 2012
所有都是表达式
                         //Java
                         int i;
                         try { i = Integer.parstInt(str);
                         } catch(NumberFormatException e) {
                           i = 0;
                         }
                         //Scala
                         val i = try { Integer.parseInt(str)
                         } catch {
                           case _:NumberFormatException => 0
                         }



Monday, April 16, 2012
XML支持

              println(<date>{new java.util.Date()}</date>)




Monday, April 16, 2012
并发


                         是什么让我们觉得一个语言是并发的语言




Monday, April 16, 2012
是什么让我们觉得Go和Erlang是并发语
                    言,而C++和Python不是




Monday, April 16, 2012
是什么让我们觉得Go和Erlang是并发语
                    言,而C++和Python不是




                     • Go内置Channel和Goroutine
                     • Erlang的一次赋值、轻量级进程


Monday, April 16, 2012
是什么让我们觉得
                          Scala是并发语言
                     • case class
                     • 模式匹配
                     • 大量的immutable类
                     • Actor
                     • Akka

Monday, April 16, 2012
Actor
                         //从Erlang学来
                         val myActor = actor {
                           loop { react {
                              case "Send" => {
                                println("Get")
                              }
                           }}
                         }
                         myActor ! "Send"




Monday, April 16, 2012
Actor

                         //增加阻塞的方案
                         val future = actor !! "msg"

                         val reply = actor !? "msg"




Monday, April 16, 2012
Akka
                         更多Erlang的功能

                     • STM & Transactors
                     • Fault-tolerance
                     • Transparent Remoting
                     • Scala & Java API

Monday, April 16, 2012
Akka

        50 million msg/sec on a single machine. Small memory
            footprint; ~2.7 million actors per GB of heap.




Monday, April 16, 2012
更多改进
                     • Unchecked exception
                     • 所有都是对象
                     • 所有都是方法(包括基础运算符)
                     • ==的语义正确了
                     • 多行字符串
                     • lazy
Monday, April 16, 2012
与Java互相调用

                     • Scala能调用绝大部分的Java
                     • 集合转换
                         JavaConverters、JavaConversions

                     • Java调用Scala独有的东西比较困难

Monday, April 16, 2012
IDE支持




Monday, April 16, 2012
缺点



Monday, April 16, 2012
It took about 15 hours to recreate the publishing daemon
  in Clojure and get it to pass all our tests. Today we ran a
  "soak test" publishing nearly 300,000 profiles in one run.
 The Scala code would fail with OoM exceptions if we hit it
      with 50,000 profiles in one run (sometimes less).



                          http://groups.google.com/group/clojure/browse_thread/thread/b18f9006c068f0a0




Monday, April 16, 2012
The e-mail confirms that Yammer is moving its basic
infrastructure stack from Scala back to Java, owing to issues
             with complexity and performance.




                                     http://www.infoq.com/news/2011/11/yammer-scala




Monday, April 16, 2012
flatMap [B, That] (f: (A)        Traversable[B])(implicit bf:
                         CanBuildFrom[List[A], B, That]) : That




                                                   http://goodstuff.im/yes-virginia-scala-is-hard




Monday, April 16, 2012
jetbrains出了新JVM语言Kotlin后,Scala社区终于开始正
              视Scala太复杂的问题了




                         http://groups.google.com/group/scalacn/browse_thread/thread/cbbe5997009db919




Monday, April 16, 2012
缺点

                     • 编译速度
                     • 二进制不兼容
                     • 语法越来越复杂
                     • 不能突破Bytecode限制
                     • 太少人使用,招聘和培训

Monday, April 16, 2012
实际使用



Monday, April 16, 2012
适用场景

                     • 单元测试
                     • 工具
                     • Socket开发
                     • 并发
                     • 任何Java实现的代码

Monday, April 16, 2012
实际遇到的问题
                     • 不用sbt会非常痛苦,但有学习成本
                     • int和Integer的转换问题依然存在
                     • 编译器启动太慢了
                     • 混合Java使用比较多问题需要解决
                     • 集合框架不给力,并且有转换问题
                     • 高级语法太晦涩了
Monday, April 16, 2012
使用建议

                     • 你应该首先是一个Java高手
                     • 不要用高级特性,除非你非常清楚
                     • 优先使用Java的类库,因为他们更成熟
                     • 立刻开始使用

Monday, April 16, 2012
开始使用

                     • 使用稳定版(2.9.1)
                     • 小工具、单元测试
                     • Java/Scala混合项目,逐步迁移
                     • sbt
                     • idea scala插件

Monday, April 16, 2012
谢谢

                     • weibo&twitter: sparklezeng
                     • email: popeast@gmail.com
                     • website: http://weavesky.com


Monday, April 16, 2012

More Related Content

PDF
OSGi Community Event 2010 - OSGi and Android
mfrancis
 
PDF
History of Java 2/2
Eberhard Wolff
 
PDF
History of java
Mani Sarkar
 
ODP
The Evolution of Java
Corneil du Plessis
 
PDF
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
David Buck
 
PDF
Java overview 20131022
hamidsamadi
 
PPTX
Java Basics
Fahad Shahzad
 
PDF
JavaCro'15 - Everything a Java EE Developer needs to know about the JavaScrip...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
OSGi Community Event 2010 - OSGi and Android
mfrancis
 
History of Java 2/2
Eberhard Wolff
 
History of java
Mani Sarkar
 
The Evolution of Java
Corneil du Plessis
 
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
David Buck
 
Java overview 20131022
hamidsamadi
 
Java Basics
Fahad Shahzad
 
JavaCro'15 - Everything a Java EE Developer needs to know about the JavaScrip...
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 

What's hot (9)

PDF
History of Java 1/2
Eberhard Wolff
 
PDF
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Miles Sabin
 
PDF
itft-Java evolution
Atul Sehdev
 
PDF
ACCU 2013 Taking Scala into the Enterpise
Peter Pilgrim
 
PDF
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
PPT
The Evolution of Java
Fu Cheng
 
PDF
QA / Testing Tools, Automation Testing, Online & Classroom Training
AnanthReddy38
 
PDF
مقدمة عن لغة سكالا
noZom Information Technology NGO
 
KEY
NOSQL also means RDF stores: an Android case study
Fabrizio Giudici
 
History of Java 1/2
Eberhard Wolff
 
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
Miles Sabin
 
itft-Java evolution
Atul Sehdev
 
ACCU 2013 Taking Scala into the Enterpise
Peter Pilgrim
 
Java Edge.2009.Grails.Web.Dev.Made.Easy
roialdaag
 
The Evolution of Java
Fu Cheng
 
QA / Testing Tools, Automation Testing, Online & Classroom Training
AnanthReddy38
 
مقدمة عن لغة سكالا
noZom Information Technology NGO
 
NOSQL also means RDF stores: an Android case study
Fabrizio Giudici
 
Ad

Viewers also liked (7)

KEY
Scala
popeast
 
PPTX
并发控制
beckrabbit
 
KEY
Golang
popeast
 
PDF
Java并发核心编程
wavefly
 
PPT
MongoDB介绍
popeast
 
PPTX
Big Data Analytics Infrastructure
Min Zhou
 
PDF
Message Queues for Web Applications
Gareth Rushgrove
 
Scala
popeast
 
并发控制
beckrabbit
 
Golang
popeast
 
Java并发核心编程
wavefly
 
MongoDB介绍
popeast
 
Big Data Analytics Infrastructure
Min Zhou
 
Message Queues for Web Applications
Gareth Rushgrove
 
Ad

Similar to Scala (20)

PPTX
Scala Introduction - Meetup Scaladores RJ
Rodrigo Lima
 
PPTX
An Introduction to Scala
Brent Lemons
 
PPTX
Scala adoption by enterprises
Mike Slinn
 
PDF
Scala for android
Tack Mobile
 
PPTX
Ten Compelling Reasons to Go the Scala Development Way - Metadesign Solutions
MetaDesign Solutions
 
PPTX
Introduction to Scala
Mohammad Hossein Rimaz
 
PDF
Scala for java developers 6 may 2017 - yeni
Baris Dere
 
PDF
JavaOne 2017 - Collections.compare:JDK, Eclipse, Guava, Apache... [CON1754]
Leonardo De Moura Rocha Lima
 
KEY
Java to scala
GiltTech
 
PDF
Scala Past, Present & Future
mircodotta
 
PDF
The Scala Programming Language
Haim Michael
 
PDF
Functional Scala 2022 - scalajs Alexis.pdf
ssusercd195b
 
PPT
Java introduction
Sagar Verma
 
PPTX
The brave new world of Java
PolyglotMeetups
 
PPTX
From java to scala at crowd mix
Stefano Galarraga
 
PPT
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Manish Pandit
 
PPTX
Scala & Spark Online Training
Learntek1
 
PPTX
Scala for n00bs by a n00b.
brandongulla
 
PDF
20091226 名古屋SGGAE/J勉強会発表資料『Lift on GAE/J』
Ryo RKTM
 
PPTX
Java basics at Lara Technologies
laratechnologies
 
Scala Introduction - Meetup Scaladores RJ
Rodrigo Lima
 
An Introduction to Scala
Brent Lemons
 
Scala adoption by enterprises
Mike Slinn
 
Scala for android
Tack Mobile
 
Ten Compelling Reasons to Go the Scala Development Way - Metadesign Solutions
MetaDesign Solutions
 
Introduction to Scala
Mohammad Hossein Rimaz
 
Scala for java developers 6 may 2017 - yeni
Baris Dere
 
JavaOne 2017 - Collections.compare:JDK, Eclipse, Guava, Apache... [CON1754]
Leonardo De Moura Rocha Lima
 
Java to scala
GiltTech
 
Scala Past, Present & Future
mircodotta
 
The Scala Programming Language
Haim Michael
 
Functional Scala 2022 - scalajs Alexis.pdf
ssusercd195b
 
Java introduction
Sagar Verma
 
The brave new world of Java
PolyglotMeetups
 
From java to scala at crowd mix
Stefano Galarraga
 
Introducing Scala to your Ruby/Java Shop : My experiences at IGN
Manish Pandit
 
Scala & Spark Online Training
Learntek1
 
Scala for n00bs by a n00b.
brandongulla
 
20091226 名古屋SGGAE/J勉強会発表資料『Lift on GAE/J』
Ryo RKTM
 
Java basics at Lara Technologies
laratechnologies
 

Recently uploaded (20)

PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
PPTX
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
A Strategic Analysis of the MVNO Wave in Emerging Markets.pdf
IPLOOK Networks
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
GDG Cloud Munich - Intro - Luiz Carneiro - #BuildWithAI - July - Abdel.pdf
Luiz Carneiro
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Doc9.....................................
SofiaCollazos
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
Responsible AI and AI Ethics - By Sylvester Ebhonu
Sylvester Ebhonu
 
Introduction to Flutter by Ayush Desai.pptx
ayushdesai204
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Peak of Data & AI Encore - Real-Time Insights & Scalable Editing with ArcGIS
Safe Software
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 

Scala

  • 1. Scala 让Java平台上的编程重现生机 Sparkle Monday, April 16, 2012
  • 2. 大纲 • Scala是什么 • 为什么选择Scala • 语法特色,与Java对比 • 缺点 • 实际使用 Monday, April 16, 2012
  • 4. "Which Programming Language would you use *now* on top of JVM, except Java?". The answer was surprisingly fast and very clear: - Scala. http://www.adam-bien.com/roller/abien/entry/java_net_javaone_which_programming Monday, April 16, 2012
  • 5. I can honestly say if someone had shown me theProgramming in Scala book by by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy. http://macstrac.blogspot.com/2009/04/scala-as-long-term-replacement-for.html Monday, April 16, 2012
  • 6. The Scala research group at EPFL is excited to announce that they have won a 5 year European Research Grant of over 2.3 million Euros to tackle the "Popular Parallel Programming" challenge. http://www.scala-lang.org/node/8579 Monday, April 16, 2012
  • 7. Scala Creator Launches Typesafe to Commercialize Modern Application Platform for Multicore and Cloud Computing. Typesafe also named to its board of advisors Java creator James Gosling and Java concurrency expert Doug Lea. http://www.marketwire.com/press-release/scala-creator-launches-typesafe-commercialize-modern-application-platform- multicore-1513767.htm Monday, April 16, 2012
  • 8. TIOBE 2012年4月份 • 45名 Monday, April 16, 2012
  • 9. TIOBE 2012年4月份 • 45名 • 3月份不在前50名 Monday, April 16, 2012
  • 10. TIOBE 2012年4月份 • 45名 • 3月份不在前50名 • (Go也不在前50名) Monday, April 16, 2012
  • 11. TIOBE 2012年4月份 • 45名 • 3月份不在前50名 • (Go也不在前50名) • (曾经进入前30名) Monday, April 16, 2012
  • 12. Scala实现 • Play 2.0 • Akka(很像Erlang的并发库) • Apollo(下一代ActiveMQ) • Spark(Hadoop竞争者) • Kafka(MQ) • Apache Camel支持Scala DSL Monday, April 16, 2012
  • 13. Scala是…… • 又一个JVM上的语言(编译型) • 强类型 • “动态的”静态语言 • 面向对象 • 函数式 • 并发 Monday, April 16, 2012
  • 14. Scala不是…… • 杀手 • 取代JVM • 突破JVM限制 • Java实现不了的功能 Monday, April 16, 2012
  • 15. Scala不是…… • 杀手 • 取代JVM • 突破JVM限制 • Java实现不了的功能 你可以认为Scala是大量语法糖的Java Monday, April 16, 2012
  • 16. 谁在用 • Twitter • LinkedIn • FourSquare • Tumblr • Bump • Xerox、Sony、Siemens Monday, April 16, 2012
  • 18. Java语法落后了 JDK 1.0 (January 23, 1996) JDK 1.1 (February 19, 1997) J2SE 1.2 (December 8, 1998) J2SE 1.3 (May 8, 2000) J2SE 1.4 (February 6, 2002) J2SE 5.0 (September 30, 2004) Java SE 6 (December 11, 2006) Java SE 7 (July 28, 2011) Monday, April 16, 2012
  • 19. 世间还有这些语言 • Erlang Python Ruby Lua C# PHP C++ Go • JRuby Groovy Clojure Monday, April 16, 2012
  • 21. 为什么选择Scala • JVM平台——技术积累 Monday, April 16, 2012
  • 22. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 Monday, April 16, 2012
  • 23. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 • 编译成Bytecode——性能保证 Monday, April 16, 2012
  • 24. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 • 编译成Bytecode——性能保证 • 函数式和OO并存——无痛切换 Monday, April 16, 2012
  • 25. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 • 编译成Bytecode——性能保证 • 函数式和OO并存——无痛切换 • 高级语法——高层抽象 Monday, April 16, 2012
  • 26. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 • 编译成Bytecode——性能保证 • 函数式和OO并存——无痛切换 • 高级语法——高层抽象 • 并发——多核的挑战 Monday, April 16, 2012
  • 27. 为什么选择Scala • JVM平台——技术积累 • 静态语言——工程化 • 编译成Bytecode——性能保证 • 函数式和OO并存——无痛切换 • 高级语法——高层抽象 • 并发——多核的挑战 • 其实Scala的学习难度并不高 Monday, April 16, 2012
  • 29. Hello, world! //Java class Test { public static void main(String[] args) { System.out.println("Hello, world!"); } } //Scala object Test { def main(args: Array[String]) { println("Hello, world!") } } Monday, April 16, 2012
  • 30. Hello, world! //Scala object Test extends Application { println("Hello, world!") } Monday, April 16, 2012
  • 31. Java Bean //Java class MyBean { private int x, y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } } //Scala class MyBean(var x: Int, var y: Int) {} Monday, April 16, 2012
  • 32. 多返回值 //Java class MyResult { //xxx } public MyResult getResult() { //xxx return new MyBean(x, y); } MyResult result = getResult(); result.getX(); Monday, April 16, 2012
  • 33. 多返回值 //Java public Object[] getResult() { //xxx return new Object[]{ x, y }; } Object result = getResult(); (String)result[0]; Monday, April 16, 2012
  • 34. 多返回值 //Scala def getResult = { //xxx (x, y, z) } val (x, _, z) = getResult Monday, April 16, 2012
  • 35. 模式匹配 def matchTest(x: Any) = x match { case 1 => "number one" case y: Int if y > 0 => y + 1 case head :: tail => tail case Send(a, _) => a case ("Send", _, b: String) => b case _ => x } //强化版switch //元素提取 Monday, April 16, 2012
  • 36. 模式匹配 //Java public boolean equals(Object obj) { if (obj instanceof Point) { Point point = (Point) obj; return x == point.x && y == point.y; } else { return false; } } Monday, April 16, 2012
  • 37. 模式匹配 //Scala def equals(any: Any) = any match { case point: Point => x == point.x && y == point.y case _ => false } Monday, April 16, 2012
  • 38. 函数式 //Java 当然你不会这样写 list.filter(new F<Integer, Boolean>() { public Boolean f(Integer i) { return i % 2 == 0; } }); //你可能经常这样写 executor.execute(new Runnable() { public void run() { //xxx } }); Monday, April 16, 2012
  • 39. 函数式 //Scala 三种写法 list.filter(e => e % 2 == 0) list.filter(_ % 2 == 0) val f = (e: Int) => e % 2 == 0 list.filter(f) Monday, April 16, 2012
  • 40. 函数式 //Scala 这里有三个循环,不一定是好习惯 list.filter(_ % 2 == 0).map(_ / 2).sum Monday, April 16, 2012
  • 41. 匿名函数 //Scala execute { println("check") } def execute(runnable: => Unit) { executor.execute(new Runnable() { def run = runnable }) } Monday, April 16, 2012
  • 42. 匿名函数 //slf4j logger.error("some error: {}, {}, {}", new Object[] {x, y, z}); //Scala msg在访问的时候才会计算! def error(msg: => String) { if(logger.isErrorEnabled) { logger.error(msg) } } error("some error: " + x + ", " + y + ", " + z) Monday, April 16, 2012
  • 43. open class(ruby) class String   def foo   "foo"   end end puts "".foo # prints "foo" Monday, April 16, 2012
  • 44. 为什么open class //这不是一个OO行为 StringUtils.isBlank("some str") //这才是OO "some str".isBlank //我们需要打开别人的类添加方法,继承并不能满足 Monday, April 16, 2012
  • 45. 为什么open class //junit hamcrest assertThat(theBiscuit, is(equalTo(myBiscuit))); //mockito verify(mockedList).add("one"); //Scala specs2 "Hello world" must startWith("Hello") //DSL !! //让第三方框架打开我们的类 Monday, April 16, 2012
  • 46. 隐式转换 class MyStr(str: String) { def isBlank = str.trim.length == 0 } implicit def myStrW(str: String) = new MyStr(str) println("some str".isBlank) Monday, April 16, 2012
  • 47. 隐式转换 class MyStr(str: String) { def isBlank = str.trim.length == 0 } implicit def myStrW(str: String) = new MyStr(str) println("some str".isBlank) println(new MyStr("some str").isBlank) Monday, April 16, 2012
  • 48. open class的效果让大家觉得Scala是动态语言,但选择隐 式转换来实现,正好证明了Scala是静态语言 Monday, April 16, 2012
  • 49. Traits //这是一个经典的Java模式 interface IAnimal {} abstract class Animal implements IAnimal { //公共代码 } class Bird extends Animal implements CanFly {} //问题来了,CanFly的公共代码写在哪里 Monday, April 16, 2012
  • 50. Traits //Scala abstract class Animal { xxx } trait CanFly { def fly { println("fly") } } class Bird extends Animal with CanFly {} Monday, April 16, 2012
  • 51. Traits class Fish { xxx } trait CanFly { def fly { println("fly") } } val flyFish = new Fish with CanFly Monday, April 16, 2012
  • 52. Traits //按照具体需求装配不同的功能 val order = new Order(customer) with MailNotifier with ACL with Versioned with Transactional Monday, April 16, 2012
  • 53. Duck Typing class Duck { def quack = "呱...呱..." } def doQuack(d: {def quack: String}) { println(d.quack) } doQuack(new Duck) Monday, April 16, 2012
  • 54. Duck Typing class Duck { def quack = "呱...呱..." } type DuckLike = { def quack: String } def doQuack(d: DuckLike) { println(d.quack) } doQuack(new Duck) //是不是有点像Go语言的感觉? Monday, April 16, 2012
  • 55. 尾递归优化 def factorial(n: Int): Int = { @tailrec def factorialAcc(acc: Int, n: Int): Int = { if (n <= 1) acc else factorialAcc(n * acc, n - 1) } factorialAcc(1, n) } //Scala会自动优化成循环,@tailrec只是确保发生优化 Monday, April 16, 2012
  • 56. 所有都是表达式 //Java int i; try { i = Integer.parstInt(str); } catch(NumberFormatException e) { i = 0; } //Scala val i = try { Integer.parseInt(str) } catch { case _:NumberFormatException => 0 } Monday, April 16, 2012
  • 57. XML支持 println(<date>{new java.util.Date()}</date>) Monday, April 16, 2012
  • 58. 并发 是什么让我们觉得一个语言是并发的语言 Monday, April 16, 2012
  • 59. 是什么让我们觉得Go和Erlang是并发语 言,而C++和Python不是 Monday, April 16, 2012
  • 60. 是什么让我们觉得Go和Erlang是并发语 言,而C++和Python不是 • Go内置Channel和Goroutine • Erlang的一次赋值、轻量级进程 Monday, April 16, 2012
  • 61. 是什么让我们觉得 Scala是并发语言 • case class • 模式匹配 • 大量的immutable类 • Actor • Akka Monday, April 16, 2012
  • 62. Actor //从Erlang学来 val myActor = actor { loop { react { case "Send" => { println("Get") } }} } myActor ! "Send" Monday, April 16, 2012
  • 63. Actor //增加阻塞的方案 val future = actor !! "msg" val reply = actor !? "msg" Monday, April 16, 2012
  • 64. Akka 更多Erlang的功能 • STM & Transactors • Fault-tolerance • Transparent Remoting • Scala & Java API Monday, April 16, 2012
  • 65. Akka 50 million msg/sec on a single machine. Small memory footprint; ~2.7 million actors per GB of heap. Monday, April 16, 2012
  • 66. 更多改进 • Unchecked exception • 所有都是对象 • 所有都是方法(包括基础运算符) • ==的语义正确了 • 多行字符串 • lazy Monday, April 16, 2012
  • 67. 与Java互相调用 • Scala能调用绝大部分的Java • 集合转换 JavaConverters、JavaConversions • Java调用Scala独有的东西比较困难 Monday, April 16, 2012
  • 70. It took about 15 hours to recreate the publishing daemon in Clojure and get it to pass all our tests. Today we ran a "soak test" publishing nearly 300,000 profiles in one run. The Scala code would fail with OoM exceptions if we hit it with 50,000 profiles in one run (sometimes less). http://groups.google.com/group/clojure/browse_thread/thread/b18f9006c068f0a0 Monday, April 16, 2012
  • 71. The e-mail confirms that Yammer is moving its basic infrastructure stack from Scala back to Java, owing to issues with complexity and performance. http://www.infoq.com/news/2011/11/yammer-scala Monday, April 16, 2012
  • 72. flatMap [B, That] (f: (A) Traversable[B])(implicit bf: CanBuildFrom[List[A], B, That]) : That http://goodstuff.im/yes-virginia-scala-is-hard Monday, April 16, 2012
  • 73. jetbrains出了新JVM语言Kotlin后,Scala社区终于开始正 视Scala太复杂的问题了 http://groups.google.com/group/scalacn/browse_thread/thread/cbbe5997009db919 Monday, April 16, 2012
  • 74. 缺点 • 编译速度 • 二进制不兼容 • 语法越来越复杂 • 不能突破Bytecode限制 • 太少人使用,招聘和培训 Monday, April 16, 2012
  • 76. 适用场景 • 单元测试 • 工具 • Socket开发 • 并发 • 任何Java实现的代码 Monday, April 16, 2012
  • 77. 实际遇到的问题 • 不用sbt会非常痛苦,但有学习成本 • int和Integer的转换问题依然存在 • 编译器启动太慢了 • 混合Java使用比较多问题需要解决 • 集合框架不给力,并且有转换问题 • 高级语法太晦涩了 Monday, April 16, 2012
  • 78. 使用建议 • 你应该首先是一个Java高手 • 不要用高级特性,除非你非常清楚 • 优先使用Java的类库,因为他们更成熟 • 立刻开始使用 Monday, April 16, 2012
  • 79. 开始使用 • 使用稳定版(2.9.1) • 小工具、单元测试 • Java/Scala混合项目,逐步迁移 • sbt • idea scala插件 Monday, April 16, 2012
  • 80. 谢谢 • weibo&twitter: sparklezeng • email: [email protected] • website: http://weavesky.com Monday, April 16, 2012