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 for Java programmers

10,130 views

Published on

Introducing Scala programming language for Java programmers.
Several functional concepts, traits, pattern matching and actors are mentioned.

Published in: Technology, News & Politics
  • Be the first to comment

Scala for Java programmers

  1. 1. Scalaf o r J a v a P r o g r a m m e r s
  2. 2. Hello, Scala!
  3. 3. Copyright © 2013 Akira Koyasu. Some rights reserved.Hello, World!3
  4. 4. Copyright © 2013 Akira Koyasu. Some rights reserved.Hello, World!object HelloWorld {def main(args: Array[String])= println("Hello, World!")}3
  5. 5. Copyright © 2013 Akira Koyasu. Some rights reserved.AgendaAbout ScalaFeatures4
  6. 6. Copyright © 2013 Akira Koyasu. Some rights reserved.MotivationScalable language. To be scalable in the sensethat the same concepts can describe small aswell as large parts.A unified and generalized object-oriented andfunctional programming language providesscalable support.From Inventor5
  7. 7. Copyright © 2013 Akira Koyasu. Some rights reserved.MotivationMore productive as “better Java” withexisting Java resources.Several concepts not in Java bring moreposibilities to you.For Java programmers6
  8. 8. Copyright © 2013 Akira Koyasu. Some rights reserved.the ProgrammingLanguageLanguage SpecificationAPIRuntime7
  9. 9. Copyright © 2013 Akira Koyasu. Some rights reserved.API8Scaladoc
  10. 10. Copyright © 2013 Akira Koyasu. Some rights reserved.Runtimescalac.scala.classthe compiler for .NETis out of dateJVMscalaRunning on JVMCompiler generatesclass files9
  11. 11. Copyright © 2013 Akira Koyasu. Some rights reserved.InfluencersJava C#SmalltalkHaskellAlgol SimulaEiffelSML F#ErlangIswimLispPythonRuby10
  12. 12. Copyright © 2013 Akira Koyasu. Some rights reserved.InventorMartin OderskyProfessor ofprogramming methods atEPFL in SwitzerlandDesigner of Javagenericsphoto#111
  13. 13. Copyright © 2013 Akira Koyasu. Some rights reserved.Object, Operatorval apple = new Appleval orange = new Orangeprintln(apple + orange)?12
  14. 14. Copyright © 2013 Akira Koyasu. Some rights reserved.Object, Operatorval apple = new Appleval orange = new Orangeprintln(apple + orange)?(A) "Apple@xxxxOrange@xxxx"(B) 2(C) Compile error(D) Runtime exception(E) Others12
  15. 15. Copyright © 2013 Akira Koyasu. Some rights reserved.FeaturesStatic typing & Suitable type inferenceObject-oriented & FunctionalTraitCollaborating with Java13
  16. 16. Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaType declarationpublic String suffix(String str) { int pos = str.indexOf("-"); return str.substring(pos);}14
  17. 17. Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaType declarationdef suffix(str: String) = {val pos = str.indexOf("-")str.substring(pos)}14
  18. 18. Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaJavaBeanspublic class JavaBeans { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; }}15
  19. 19. Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaJavaBeanscase class ScalaCase(name: String)15
  20. 20. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingvariablesmethod parametersmethod returnsFunctions are the first-class values16
  21. 21. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingConsider a method signature sending mails toappropriate addresses from listingdef send() {for(c: Contact <- listing()) {mail(c)}}17
  22. 22. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgramming18
  23. 23. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2018
  24. 24. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==20 def send(age: Int)18
  25. 25. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60def send(age: Int)18
  26. 26. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60def send(age: Int)def send(minAge: Int, maxAge: Int)18
  27. 27. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60age<30, gender:Maledef send(age: Int)def send(minAge: Int, maxAge: Int)18
  28. 28. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60age<30, gender:Maledef send(age: Int)def send(minAge: Int, maxAge: Int)def send(minAge: Int, maxAge: Int, g: Gender)18
  29. 29. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60age<30, gender:Malegender:Female, in Tokyodef send(age: Int)def send(minAge: Int, maxAge: Int)def send(minAge: Int, maxAge: Int, g: Gender)18
  30. 30. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60age<30, gender:Malegender:Female, in Tokyodef send(age: Int)def send(minAge: Int, maxAge: Int)def send(minAge: Int, maxAge: Int, g: Gender)def send(minAge: Int, maxAge: Int, g: Gender, pref: String)18
  31. 31. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingdef send(p: Contact => Boolean) {for(c: Contact <- listing()) {if (p(c)) mail(c)}}Apply condition function to method19
  32. 32. Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingy = f(x)Avoiding side effectsConscious of immutability20
  33. 33. Copyright © 2013 Akira Koyasu. Some rights reserved.Partially appliedFunction21def sum(a: Int, b: Int, c: Int) = a + b + cval f1 = sum _val f2 = sum(1, _: Int, 3)def main(args: Array[String]) {println(f1(1, 2, 3)) // 6println(f2(2)) // 6println(f2(5)) // 9}
  34. 34. Copyright © 2013 Akira Koyasu. Some rights reserved.Curried Function22def sum(a: Int)(b: Int) = a + bdef main(args: Array[String]) {println(sum(1)(2)) // 3}
  35. 35. Copyright © 2013 Akira Koyasu. Some rights reserved.Curried Function23def withResource(r: Closeable)(op: => Unit) {try {op} finally {r.close()}} def main(args: Array[String]) {val writer = new FileWriter("test.txt")withResource(writer) {writer.write("foo bar")}}
  36. 36. Copyright © 2013 Akira Koyasu. Some rights reserved.Traita special form of an abstract classwhich can be used as mixins24
  37. 37. Copyright © 2013 Akira Koyasu. Some rights reserved.Trait25to enrich interfaceclass MyInt(val n: Int) extends Ordered[MyInt] {def compare(that: MyInt)= this.n - that.n}val n1 = new MyInt(1)val n2 = new MyInt(2)println(n1 < n2)println(n1 > n2)println(n1 <= n2)println(n1 >= n2)
  38. 38. Copyright © 2013 Akira Koyasu. Some rights reserved.Trait26stackable modificationsabstract class Sale {def price(): Double}class BasicSale extends Sale {def price() = 100;}trait OffTenPercent extends Sale {abstract overridedef price() = { super.price.toDouble * 0.9 }}trait OffTwenty extends Sale {abstract overridedef price() = { super.price - 20 }}-10%-¥20¥100
  39. 39. Copyright © 2013 Akira Koyasu. Some rights reserved.Trait27stackable modificationsclass UnbelievableSaleextends BasicSale with OffTenPercentclass UnbelievableSale2extends BasicSale with OffTwentyclass UnbelievableSale3extends BasicSale with OffTenPercent with OffTwentyclass UnbelievableSale4extends BasicSale with OffTwenty with OffTenPercentdef main(args: Array[String]) {println((new BasicSale).price) // 100.0println((new UnbelievableSale).price) // 90.0println((new UnbelievableSale2).price) // 80.0println((new UnbelievableSale3).price) // 70.0println((new UnbelievableSale4).price) // 72.0}-10%-¥20-10%, -¥20-¥20, -10%
  40. 40. Copyright © 2013 Akira Koyasu. Some rights reserved.Pattern Match28case class ScalaCase(name: String)def test(x: Any) = x match {case 1 => println("1")case str: String => println(str)case ScalaCase(name) => println("name: " + name)case _ => println("other")}def main(args: Array[String]) {test(1) // 1test("Hello!") // Hello!test(ScalaCase("apple")) // name: appletest(2.5) // other}
  41. 41. Copyright © 2013 Akira Koyasu. Some rights reserved.29
  42. 42. Scala in Action
  43. 43. Copyright © 2013 Akira Koyasu. Some rights reserved.CollectionOperation31getting the highest score in 2013case class Student(year: Int, score: Int)def students(): List[Student] =List(Student(2013, 92), Student(2012, 98), Student(2013, 70))def students2(): List[Student] =Student(2013, 92)::Student(2012, 98)::Student(2013, 70)::Nildef highestScoreIn2013() = students().filter(s => s.year == 2013).map(s => s.score).foldLeft(0)((a, b) => max(a, b))
  44. 44. Copyright © 2013 Akira Koyasu. Some rights reserved.Actor32actorAactorBactorCactorDNo shared dataExchanging messagesConcurrency model
  45. 45. Copyright © 2013 Akira Koyasu. Some rights reserved.Actor (Akka)33object Actors {implicit val system = ActorSystem("MySystem")val a, b = actor(new Act {become {case ("ping", actor: ActorRef) => {println("received ping")Thread.sleep(1000)actor ! ("pong", self)}case ("pong", actor: ActorRef) => {println("received pong")Thread.sleep(1000)actor ! ("ping", self)}}})def main(args: Array[String]) {a ! ("ping", b)}}received pingreceived pongreceived pingreceived pongreceived pingreceived pong...
  46. 46. Copyright © 2013 Akira Koyasu. Some rights reserved.Practical Scala34
  47. 47. Copyright © 2013 Akira Koyasu. Some rights reserved.Practical ScalaKiller framework Play (+)Java on the bench (+)Interactive shell (+)There are many concepts (-)the compiler needs more resources (-)Backward compatibility? (-)34
  48. 48. Copyright © 2013 Akira Koyasu. Some rights reserved.Next StepImplicit conversionsExtractorAbstract typeType parameter & variance35
  49. 49. Copyright © 2013 Akira Koyasu. Some rights reserved.ReferenceAn Overview of the Scala ProgrammingLanguage Second Edition (pdf)A Scala Tutorial for Java programmers (pdf)Programming in Scala, Second Edition(Japanese version: Scala スケーラブルプログラミング 第2版)36
  50. 50. Copyright © 2013 Akira Koyasu. Some rights reserved.NotesThis work is licensed under the Creative Commons Attribution-NonCommercial 3.0 Unported License. To view a copy of thislicense, visit http://creativecommons.org/licenses/by-nc/3.0/.37photo#1: http://en.wikipedia.org/wiki/File:Mark_Odersky_photo_by_Linda_Poeng.jpgFeed backs Welcome!http://twitter.com/akirakoyasuhttp://fb.me/akirakoyasu
  51. 51. Thank you!

×