Scala the next … ?ŁukaszKuczera
Java
PHP
Python
ScalaHybrid Object-Functional With type inferentionDuck typingAnd multiple inheritanceCompiles to JVM and CLR
Scalable
History
1995Well no but, lets do some functional programming in Java !!Have you seen Martin this Java thing that “runs everywhere” ?
Pizza
Martin OderskyGiladBrachaPhillWadlerDavid StoutamireScalaNewspeakHaskell
Funnel – 1999Scala – 2003
Scala bread and butter
IDE  EclipseNetBeans  IDEAEmacs  VimTextMate
Enough of blabberingshow us the code !
class Test {// variable definitionvarn: Int= 5// value definitionvali= 10// function definitiondefsum(i:Int, n:Int):Int=i+ndefprintit(x: Any)=println(x)} object Basics extends Test {overridevali= 20overridedef sum(i:Int, n:Int):Int=i+ndef main(args: Array[String]){printit(sum(i,n))}}
Objects and Operators 3 +4 5 % 2 3 * 3valtest =new Testtest printit"hello world !” classOpOverloading{def+(x: Any)=println("I'm + function/operator") }== 3.+(4)==5.%(2)== 3.*(3)
Rational ExampleclassRational(vali:Int,val n:Int){defthis(i:Int)=this(i, 1)def*(other:Rational)=new Rational(i*other.i, n *other.n)overridedeftoString=i+"/"+ ndef*(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 unleashedclassRational(vali:Int,val n:Int){defthis(i:Int)=this(i, 1)def*(other:Rational)=new Rational(i*other.i, n *other.n)overridedeftoString=i+"/"+ ndef*(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 errorimplicitdef int2rational(i:Int)=new Rational(i)  3 * quarter // == 3/4
Pimp my librarypattern
DSL
 Internal DSL’s in ScalaMenu.i("Home")/”home” / *>>loggedIn>>User.AddUserMenusAfteremployee 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 ENDRUN}}
And JavaScriptAppendHtml("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 - JavapublicclassPerson{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 - JavaclassPartition{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 - Scalavalall = Array[Person]()val(minors, adults)=all.partition(_.age < 18)
Reduce - JavaclassReduce{List<Person>all;intsum=0;for(Personp: all){sum+=p.getAge();}}
Reduce - Scalavalall = Array[Person]()all.map(_.age).reduce(_+_)
Sort - JavaclassSort{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 - Scalavalall = Array[Person]()all.sortBy(_.age)
Objects as Functions valadder =(x: Int)=> x + 1val 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 + 1adder.apply(1)// == 2adder.apply(5) // == 6defhigherOrderFunction(f:(Int=>Int), x:Int)= f(x)higherOrderFunction(adder, 1)
Structural (Duck) TypingdefdoIn(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 listsdefdoIn(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 ParametersdefdoIn(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)
XMLval 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)).mkStringprintln(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).openConnectionval reader =newBufferedReader(newInputStreamReader(con.getInputStream,"ISO-8859-1"))var line ="";while(line !=null){      line =reader.readLineif(line !=null)println(line)}con.getInputStream.close})
Nulls - JavaMap<String, String>capitals=newHashMap<String, String>();capitals.put("Poland","Warsaw");System.out.println(capitals.get("Polska").trim());Exceptionin thread "main"java.lang.NullPointerException
Nulls - Scalaval 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 thanJava 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 FeaturesTypeInferenceUniform Access PrincipleClosuresCuryingHigher Order FunctionsPatternMatchingActorsGenerics (covariance, higher order kinds)Native XML supportAbstractcontrolstructuresImplicitconversions and parametersAdvanced for expressionsAnnotationsCombinatorparsingTraitsDucktypingNull „safety” (Option Type)
Join me and together we will rule the galaxy !
About Me	l.kuczera@jextreme.pllkuczera              http://acidbits.org/blog              http://github.com/lkuczera/lift-blog

Scala 3camp 2011

  • 1.
    Scala the next… ?ŁukaszKuczera
  • 2.
  • 3.
  • 4.
  • 5.
    ScalaHybrid Object-Functional Withtype inferentionDuck typingAnd multiple inheritanceCompiles to JVM and CLR
  • 6.
  • 7.
  • 8.
    1995Well no but,lets do some functional programming in Java !!Have you seen Martin this Java thing that “runs everywhere” ?
  • 9.
  • 10.
  • 12.
  • 13.
  • 14.
    IDE EclipseNetBeans IDEAEmacs VimTextMate
  • 15.
  • 16.
    class Test {//variable definitionvarn: Int= 5// value definitionvali= 10// function definitiondefsum(i:Int, n:Int):Int=i+ndefprintit(x: Any)=println(x)} object Basics extends Test {overridevali= 20overridedef sum(i:Int, n:Int):Int=i+ndef main(args: Array[String]){printit(sum(i,n))}}
  • 17.
    Objects and Operators3 +4 5 % 2 3 * 3valtest =new Testtest printit"hello world !” classOpOverloading{def+(x: Any)=println("I'm + function/operator") }== 3.+(4)==5.%(2)== 3.*(3)
  • 18.
    Rational ExampleclassRational(vali:Int,val n:Int){defthis(i:Int)=this(i,1)def*(other:Rational)=new Rational(i*other.i, n *other.n)overridedeftoString=i+"/"+ ndef*(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 !
  • 19.
    Do not underestimatethe power of Scala !
  • 20.
    Implicit definitions unleashedclassRational(vali:Int,valn:Int){defthis(i:Int)=this(i, 1)def*(other:Rational)=new Rational(i*other.i, n *other.n)overridedeftoString=i+"/"+ ndef*(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 errorimplicitdef int2rational(i:Int)=new Rational(i) 3 * quarter // == 3/4
  • 21.
  • 22.
  • 23.
    Internal DSL’sin ScalaMenu.i("Home")/”home” / *>>loggedIn>>User.AddUserMenusAfteremployee 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)}
  • 24.
    object Lunar extendsBaysick{defmain(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 ENDRUN}}
  • 25.
    And JavaScriptAppendHtml("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('')")
  • 26.
    Class Parameters -JavapublicclassPerson{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;}}
  • 27.
    Class Parameters -Scala classPerson(var name: String,var age:Int)
  • 28.
  • 29.
    Partition - Scalavalall= Array[Person]()val(minors, adults)=all.partition(_.age < 18)
  • 30.
  • 31.
    Reduce - Scalavalall= Array[Person]()all.map(_.age).reduce(_+_)
  • 32.
    Sort - JavaclassSort{List<Person>all;Comparator<Person>comp=newComparator<Person>(){publicint compare(p1: Person, p2: Person){return p1.getAge()- p2.getAge();}};Collections.sort(all, comp);}
  • 33.
    Sort - Scalavalall= Array[Person]()all.sortBy(_.age)
  • 34.
    Objects as Functionsvaladder =(x: Int)=> x + 1val anonfun1 =new Function1[Int, Int]{def apply(x:Int):Int= x + 1} adder(1) // == 2 anonfun1(5) // == 6
  • 35.
    Functions as Objectsvaladder =(x: Int)=> x + 1adder.apply(1)// == 2adder.apply(5) // == 6defhigherOrderFunction(f:(Int=>Int), x:Int)= f(x)higherOrderFunction(adder, 1)
  • 36.
    Structural (Duck) TypingdefdoIn(resource:{defopen(): 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
  • 37.
    Multiple parameter listsdefdoIn(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)
  • 38.
    Implicit ParametersdefdoIn(code:()=> Unit)(implicitresource:{def open(): Unit;def close(): Unit }){resource.open(); code()resource.close();}implicitval a =newScalaObject{def open(){}def close(){}}doIn(()=>{// do some useful stuff ...}) (a)
  • 39.
    XMLval person =<personname="ŁukaszKuczera"><addressvoivodeship="Pomorskie"><city>Gdańsk</city></address></person>valname= person \"@name”valaddress = person \"address"valcity = address \"city”val_city = person \\"city"
  • 40.
    val xml =<divclass="rsswidget"><ul><li><ahref="http://www.quotationspage.com/qotd.html">Quotesof 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)).mkStringprintln(quote)})
  • 41.
    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).openConnectionval reader =newBufferedReader(newInputStreamReader(con.getInputStream,"ISO-8859-1"))var line ="";while(line !=null){ line =reader.readLineif(line !=null)println(line)}con.getInputStream.close})
  • 42.
    Nulls - JavaMap<String,String>capitals=newHashMap<String, String>();capitals.put("Poland","Warsaw");System.out.println(capitals.get("Polska").trim());Exceptionin thread "main"java.lang.NullPointerException
  • 43.
    Nulls - Scalavalcapitals = 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")
  • 44.
  • 45.
    If I whereto choose language other thanJava it would be Scala
  • 46.
    „I can honestlysay 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”
  • 47.
    „Scala, it mustbe 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”
  • 48.
    Scala FeaturesTypeInferenceUniform AccessPrincipleClosuresCuryingHigher Order FunctionsPatternMatchingActorsGenerics (covariance, higher order kinds)Native XML supportAbstractcontrolstructuresImplicitconversions and parametersAdvanced for expressionsAnnotationsCombinatorparsingTraitsDucktypingNull „safety” (Option Type)
  • 49.
    Join me andtogether we will rule the galaxy !
  • 50.
    About Me l.kuczera@jextreme.pllkuczera http://acidbits.org/blog http://github.com/lkuczera/lift-blog

Editor's Notes

  • #3 Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • #4 Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • #5 Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • #7 Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  • #8 David pollackMesa spreadsheet
  • #13 David pollackMesa spreadsheet
  • #14 David pollackMesa spreadsheet
  • #16 David pollackMesa spreadsheet
  • #18 Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • #19 Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • #21 Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  • #22 Pozwalanarozszerzanieistniejącychklas
  • #23 Pozwalanarozszerzanieistniejącychklasbezkoniecznościzmian
  • #25 W czym to jest napisane ?
  • #35 Obie formysąrównoznaczne
  • #51 dfasdfadfladkj