Scala for Java programmers
Upcoming SlideShare
Loading in...5
×
 

Scala for Java programmers

on

  • 3,411 views

Introducing Scala programming language for Java programmers.

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

Statistics

Views

Total Views
3,411
Views on SlideShare
1,371
Embed Views
2,040

Actions

Likes
3
Downloads
36
Comments
0

7 Embeds 2,040

http://www.akirakoyasu.net 1648
http://www.scoop.it 372
https://twitter.com 8
http://www.google.co.jp 8
http://cloud.feedly.com 2
http://reader.aol.com 1
http://webcache.googleusercontent.com 1
More...

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Scala for Java programmers Scala for Java programmers Presentation Transcript

  • Scalaf o r J a v a P r o g r a m m e r s
  • Hello, Scala!
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Hello, World!3
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Hello, World!object HelloWorld {def main(args: Array[String])= println("Hello, World!")}3
  • Copyright © 2013 Akira Koyasu. Some rights reserved.AgendaAbout ScalaFeatures4
  • 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
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.the ProgrammingLanguageLanguage SpecificationAPIRuntime7
  • Copyright © 2013 Akira Koyasu. Some rights reserved.API8Scaladoc
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Runtimescalac.scala.classthe compiler for .NETis out of dateJVMscalaRunning on JVMCompiler generatesclass files9
  • Copyright © 2013 Akira Koyasu. Some rights reserved.InfluencersJava C#SmalltalkHaskellAlgol SimulaEiffelSML F#ErlangIswimLispPythonRuby10
  • Copyright © 2013 Akira Koyasu. Some rights reserved.InventorMartin OderskyProfessor ofprogramming methods atEPFL in SwitzerlandDesigner of Javagenericsphoto#111
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Object, Operatorval apple = new Appleval orange = new Orangeprintln(apple + orange)?12
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FeaturesStatic typing & Suitable type inferenceObject-oriented & FunctionalTraitCollaborating with Java13
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaType declarationpublic String suffix(String str) { int pos = str.indexOf("-"); return str.substring(pos);}14
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaType declarationdef suffix(str: String) = {val pos = str.indexOf("-")str.substring(pos)}14
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Vorbose JavaJavaBeanscase class ScalaCase(name: String)15
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingvariablesmethod parametersmethod returnsFunctions are the first-class values16
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgramming18
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2018
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==20 def send(age: Int)18
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60def send(age: Int)18
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingage==2035<=age, age<=60def send(age: Int)def send(minAge: Int, maxAge: Int)18
  • 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
  • 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
  • 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
  • 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
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.FunctionalProgrammingy = f(x)Avoiding side effectsConscious of immutability20
  • 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}
  • 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}
  • 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")}}
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Traita special form of an abstract classwhich can be used as mixins24
  • 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)
  • 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
  • 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%
  • 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}
  • Copyright © 2013 Akira Koyasu. Some rights reserved.29
  • Scala in Action
  • 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))
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Actor32actorAactorBactorCactorDNo shared dataExchanging messagesConcurrency model
  • 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...
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Practical Scala34
  • 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
  • Copyright © 2013 Akira Koyasu. Some rights reserved.Next StepImplicit conversionsExtractorAbstract typeType parameter & variance35
  • 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
  • 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
  • Thank you!