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
PDF
History of Java 2/2
PDF
History of java
ODP
The Evolution of Java
PDF
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
PDF
Java overview 20131022
PPTX
Java Basics
PDF
JavaCro'15 - Everything a Java EE Developer needs to know about the JavaScrip...
OSGi Community Event 2010 - OSGi and Android
History of Java 2/2
History of java
The Evolution of Java
InvokeDynamic for Mere Mortals [JavaOne 2015 CON7682]
Java overview 20131022
Java Basics
JavaCro'15 - Everything a Java EE Developer needs to know about the JavaScrip...

What's hot (9)

PDF
History of Java 1/2
PDF
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
PDF
itft-Java evolution
PDF
ACCU 2013 Taking Scala into the Enterpise
PDF
Java Edge.2009.Grails.Web.Dev.Made.Easy
PPT
The Evolution of Java
PDF
QA / Testing Tools, Automation Testing, Online & Classroom Training
PDF
مقدمة عن لغة سكالا
KEY
NOSQL also means RDF stores: an Android case study
History of Java 1/2
Scaladays 2010 - The Scala IDE for Eclipse - Retrospect and Prospect for 2.8 ...
itft-Java evolution
ACCU 2013 Taking Scala into the Enterpise
Java Edge.2009.Grails.Web.Dev.Made.Easy
The Evolution of Java
QA / Testing Tools, Automation Testing, Online & Classroom Training
مقدمة عن لغة سكالا
NOSQL also means RDF stores: an Android case study
Ad

Viewers also liked (7)

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

Similar to Scala (20)

PPTX
Scala adoption by enterprises
PDF
Absorbing Scala Into Java Ecosystem
PPTX
All about scala
PPTX
Introduction to Scala
KEY
Scala Introduction
PDF
Martin Odersky: What's next for Scala
PDF
Selling Scala to your boss
PDF
Scala, Akka, and Play: An Introduction on Heroku
PDF
Scala Sjug 09
PDF
The Forces Driving Java
PDF
Scala and jvm_languages_praveen_technologist
PPTX
An Introduction to Scala
PDF
Yes scala can!
KEY
Java to Scala: Why & How
PDF
Building Languages for the JVM - StarTechConf 2011
PDF
Java in the Age of the JVM
PPTX
Scala-Ls1
PPT
Why scala - executive overview
PPTX
Ten Compelling Reasons to Go the Scala Development Way - Metadesign Solutions
ODP
A Tour Of Scala
Scala adoption by enterprises
Absorbing Scala Into Java Ecosystem
All about scala
Introduction to Scala
Scala Introduction
Martin Odersky: What's next for Scala
Selling Scala to your boss
Scala, Akka, and Play: An Introduction on Heroku
Scala Sjug 09
The Forces Driving Java
Scala and jvm_languages_praveen_technologist
An Introduction to Scala
Yes scala can!
Java to Scala: Why & How
Building Languages for the JVM - StarTechConf 2011
Java in the Age of the JVM
Scala-Ls1
Why scala - executive overview
Ten Compelling Reasons to Go the Scala Development Way - Metadesign Solutions
A Tour Of Scala

Recently uploaded (20)

PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PPTX
1. Introduction to Computer Programming.pptx
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Approach and Philosophy of On baking technology
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
project resource management chapter-09.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
A novel scalable deep ensemble learning framework for big data classification...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Heart disease approach using modified random forest and particle swarm optimi...
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Getting Started with Data Integration: FME Form 101
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PDF
August Patch Tuesday
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
1. Introduction to Computer Programming.pptx
Univ-Connecticut-ChatGPT-Presentaion.pdf
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
DP Operators-handbook-extract for the Mautical Institute
Approach and Philosophy of On baking technology
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
project resource management chapter-09.pdf
MIND Revenue Release Quarter 2 2025 Press Release
SOPHOS-XG Firewall Administrator PPT.pptx
A novel scalable deep ensemble learning framework for big data classification...
Digital-Transformation-Roadmap-for-Companies.pptx
Heart disease approach using modified random forest and particle swarm optimi...
A comparative study of natural language inference in Swahili using monolingua...
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Getting Started with Data Integration: FME Form 101
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
Group 1 Presentation -Planning and Decision Making .pptx
NewMind AI Weekly Chronicles - August'25-Week II
August Patch Tuesday

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: popeast@gmail.com • website: http://weavesky.com Monday, April 16, 2012