Scala   3camp 2011
Upcoming SlideShare
Loading in...5
×
 

Scala 3camp 2011

on

  • 1,285 views

Scala presentation for 3camp June 2011

Scala presentation for 3camp June 2011

Statistics

Views

Total Views
1,285
Views on SlideShare
1,250
Embed Views
35

Actions

Likes
0
Downloads
19
Comments
0

2 Embeds 35

https://www.linkedin.com 29
http://www.linkedin.com 6

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • David pollackMesa spreadsheet
  • David pollackMesa spreadsheet
  • David pollackMesa spreadsheet
  • David pollackMesa spreadsheet
  • Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • Pozwalanarozszerzanieistniejącychklas
  • Pozwalanarozszerzanieistniejącychklasbezkoniecznościzmian
  • W czym to jest napisane ?
  • Obie formysąrównoznaczne
  • dfasdfadfladkj

Scala   3camp 2011 Scala 3camp 2011 Presentation Transcript

  • Scala the next … ?
    ŁukaszKuczera
  • Java
  • PHP
  • Python
  • Scala
    Hybrid Object-Functional
    With type inferention
    Duck typing
    And multiple inheritance
    Compiles to JVM and CLR
  • Scalable
  • History
  • 1995
    Well no but, lets do some functional programming in Java !!
    Have you seen Martin this Java thing that “runs everywhere” ?
  • Pizza
  • Martin Odersky
    GiladBracha
    PhillWadler
    David Stoutamire
    Scala
    Newspeak
    Haskell
  • Funnel – 1999Scala – 2003
  • Scala bread and butter
  • IDE
    Eclipse
    NetBeans
    IDEA
    Emacs
    Vim
    TextMate
  • Enough of blabberingshow us the code !
  • class Test {
    // variable definition
    varn: Int= 5
    // value definition
    vali= 10
    // function definition
    defsum(i:Int, n:Int):Int=i+n
    defprintit(x: Any)=println(x)
    }
     
    object Basics extends Test {
    overridevali= 20
    overridedef sum(i:Int, n:Int):Int=i+n
    def main(args: Array[String]){
    printit(sum(i,n))
    }
    }
  • Objects and Operators
    3 +4
    5 % 2
    3 * 3
    valtest =new Test
    test printit"hello world !”
    classOpOverloading{
    def+(x: Any)=println("I'm + function/operator")
    }
    == 3.+(4)
    ==5.%(2)
    == 3.*(3)
  • Rational Example
    classRational(vali:Int,val n:Int){
    defthis(i:Int)=this(i, 1)
    def*(other:Rational)=new Rational(i*other.i, n *other.n)
    overridedeftoString=i+"/"+ n
    def*(other:Int)=newRational(i* other, n)
    }
    valthird =new Rational(1, 3)
    val quarter =new Rational(1, 4)
    third * quarter // == 1/12
    third *3 // compilation error !
    third * 3 // == 1/9
    3 * quarter // compilation error !
  • Do not underestimate the power of Scala !
  • Implicit definitions unleashed
    classRational(vali:Int,val n:Int){
    defthis(i:Int)=this(i, 1)
    def*(other:Rational)=new Rational(i*other.i, n *other.n)
    overridedeftoString=i+"/"+ n
    def*(other:Int)=newRational(i* other, n)
    }
    valthird =new Rational(1, 3)
    val quarter =new Rational(1, 4)
    third * quarter // == 1/12
    third * 3 // compilation error !
    third * 3 // == 1/9
    3 * quarter // compilation error
    implicitdef int2rational(i:Int)=new Rational(i)
    3 * quarter // == 3/4
  • Pimp my librarypattern
  • DSL
  • Internal DSL’s in Scala
    Menu.i("Home")/”home” / *>>loggedIn>>User.AddUserMenusAfter
    employee salary for 2.weeks minus deductions for{ gross =>
    federalIncomeTax is (25. percent_of gross)
    stateIncomeTax is (5. percent_of gross)
    insurancePremiums are (500. in gross.currency)
    retirementFundContributions are (10. percent_of gross)
    }
  • object Lunar extendsBaysick{
    def main(args:Array[String])={
    10 PRINT "Welcome to Baysick Lunar Lander v0.9"
    20 LET ('dist:= 100)
    30 LET ('v := 1)
    40 LET ('fuel := 1000)
    50 LET ('mass:=1000)
    60 PRINT "Youaredriftingtowardsthemoon."
    70 PRINT "You must decidehowmuchfueltoburn."
    80 PRINT "Toaccelerateenter a positive number"
    90 PRINT "Todecelerate a negative"
    100 PRINT "Distance "% 'dist%"km, "%"Velocity "% 'v %"km/s, "%"Fuel "% 'fuel
    110 INPUT 'burn
    120 IF ABS('burn)<= 'fuel THEN 150
    130 PRINT "Youdon'thavethatmuch fuel"
    140 GOTO 100
    150 LET ('v := 'v + 'burn* 10 /('fuel + 'mass))
    160 LET ('fuel := 'fuel - ABS('burn))
    170 LET ('dist:= 'dist- 'v)
    180 IF 'dist> 0 THEN 100
    190 PRINT "Youhave hit thesurface"
    200 IF 'v < 3 THEN 240
    210 PRINT "Hit surface too fast ("% 'v %")km/s"
    220 PRINT "You Crashed!"
    230 GOTO 250
    240 PRINT "Welldone"
    250 END
    RUN
    }
    }
  • And JavaScript
    AppendHtml("comments",<xml:group>
    <divclass={className}>
    <span>{privateSpanText}</span><br/>
    <b>Author:</b>{user.firstName}{user.lastName}
    <span>added at:{comm.createdAt}</span><br/>
    <div>{ Unparsed(comm.text)}</div>
    </div>
    </xml:group>)&
    FadeOut("commentInput", 200, 200)&
    FadeOut("privateCommentField",200, 200)&
    Run("document.getElementById('private').checked = false;")&
    Run("document.getElementById('uniform-private').childNodes [0].removeAttribute('class');")&
    FadeOut("commentPrivateBox", 200, 200)&
    Run("tinyMCE.get('commentEditor').setContent('')")
  • Class Parameters - Java
    publicclassPerson{
    privateStringname;
    privateintage;
    publicPerson(String name,int age){
    this.name= name;
    this.age= age;
    }
    publicStringgetName(){
    returnname;
    }
    publicvoidsetName(String name){
    this.name= name;
    }
    publicintgetAge(){
    returnage;
    }
    publicvoidsetAge(int age){
    this.age= age;
    }
    }
  • Class Parameters - Scala
    classPerson(var name: String,var age:Int)
  • Partition - Java
    classPartition{
    List<Person>all;
    List<Person>adults=newArrayList<Person>();
    List<Person>minors=newArrayList<Person>();
    for(Personp: all){
    if(p.getAge()<18){
    minors.add(p);
    }else{
    adults.add(p);
    }
    }
    }
  • Partition - Scala
    valall = Array[Person]()
    val(minors, adults)=all.partition(_.age < 18)
  • Reduce - Java
    classReduce{
    List<Person>all;
    intsum=0;
    for(Personp: all){
    sum+=p.getAge();
    }
    }
  • Reduce - Scala
    valall = Array[Person]()
    all.map(_.age).reduce(_+_)
  • Sort - Java
    classSort{
    List<Person>all;
    Comparator<Person>comp=new Comparator<Person>(){
    publicint compare(p1: Person, p2: Person){
    return p1.getAge()- p2.getAge();
    }
    };
    Collections.sort(all, comp);
    }
  • Sort - Scala
    valall = Array[Person]()
    all.sortBy(_.age)
  • Objects as Functions
    valadder =(x: Int)=> x + 1
    val anonfun1 =new Function1[Int, Int]{
    def apply(x:Int):Int= x + 1
    }
    adder(1) // == 2
    anonfun1(5) // == 6
  • Functions as Objects
    valadder =(x: Int)=> x + 1
    adder.apply(1)// == 2
    adder.apply(5) // == 6
    defhigherOrderFunction(f:(Int=>Int), x:Int)= f(x)
    higherOrderFunction(adder, 1)
  • Structural (Duck) Typing
    defdoIn(resource:{def open(): Unit;def close(): Unit }){
    resource.open();
    // do some useful stuff ...
    resource.close();
    }
    val a =newScalaObject{
    def open(){}
    def close(){}
    }
    val b =newScalaObject{
    def open(){}
    // def close() {}
    }
    doIn(a)
    doIn(b)// compilation error
  • Multiple parameter lists
    defdoIn(code:()=> Unit)
    (resource:{def open(): Unit;def close(): Unit }){
    resource.open();
    code()
    resource.close();
    }
    doIn(()=>{
    // do some useful stuff ...
    })(a)
    defmyUsefulFunc(){
    // lots of lots of wonderful code ..
    }
    doIn(myUsefulFunc)(a)
  • Implicit Parameters
    defdoIn(code:()=> Unit)
    (implicit resource:{def open(): Unit;def close(): Unit }){
    resource.open();
    code()
    resource.close();
    }
    implicitval a =newScalaObject{
    def open(){}
    def close(){}
    }
    doIn(()=>{
    // do some useful stuff ...
    })
    (a)
  • XML
    val person =<personname="ŁukaszKuczera">
    <addressvoivodeship="Pomorskie">
    <city>Gdańsk</city>
    </address>
    </person>
    valname = person "@name”
    valaddress = person "address"
    valcity = address "city”
    val_city = person "city"
  • val xml =
    <divclass="rsswidget">
    <ul>
    <li><ahref="http://www.quotationspage.com/qotd.html">
    Quotes of the Day</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/C._P._Snow">
    C. P. Snow</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/ unknown">unknown</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/Frederick_Locker- Lampson">Frederick Locker-Lampson</a></li>
    </ul>
    </div>
    (xml "@href").slice(1, 4).foreach(url=>{
    val quote =Source.fromURL(new URL(url.text)).mkString
    println(quote)
    })
  • valxml =
    <divclass="rsswidget">
    <ul><li>
    <ahref="http://www.quotationspage.com/qotd.html">Quotes of the Day</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/C._P._Snow">
    C. P. Snow</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/unknown">unknown</a></li>
    <li><ahref="http://www.quotationspage.com/quotes/Frederick_Locker- Lampson">Frederick Locker-Lampson</a></li>
    </ul>
    </div>
    (xml "@href").slice(1, 4).foreach(url=>{
    valcon =new URL(url.toString).openConnection
    val reader =newBufferedReader(newInputStreamReader(con.getInputStream,"ISO-8859-1"))
    var line ="";
    while(line !=null){
    line =reader.readLine
    if(line !=null)println(line)
    }
    con.getInputStream.close
    })
  • Nulls - Java
    Map<String, String>capitals=
    newHashMap<String, String>();
    capitals.put("Poland","Warsaw");
    System.out.println(capitals.get("Polska").trim());
    Exceptionin thread "main"java.lang.NullPointerException
  • Nulls - Scala
    val capitals = Map("Poland"->"Warsaw");
    valcapitalOption:Option[String]=capitals.get("Polska")
    capitalOptionmatch{
    caseSome(value)=>println(value)
    caseNone =>println("Not found")
    case_=>
    }
    if(capitalOption.isDefined)println(capitalOption.get)
    println(capitalOptiongetOrElse"Not found")
  • Who uses Scala already
  • If I where to choose language other than
    Java it would be
    Scala
  • „I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created
    Groovy”
  • „Scala, it must be stated, is the current heir apparent to the Java throne. No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable”
  • Scala Features
    TypeInference
    Uniform Access Principle
    Closures
    Curying
    Higher Order Functions
    PatternMatching
    Actors
    Generics (covariance, higher order kinds)
    Native XML support
    Abstractcontrolstructures
    Implicitconversions and parameters
    Advanced for expressions
    Annotations
    Combinatorparsing
    Traits
    Ducktyping
    Null „safety” (Option Type)
  • Join me and together we will rule the galaxy !
  • About Me
    l.kuczera@jextreme.pl
    lkuczera
    http://acidbits.org/blog
    http://github.com/lkuczera/lift-blog