SlideShare une entreprise Scribd logo
1  sur  50
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 quot;@name” valaddress = person quot;address" valcity = address quot;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

Contenu connexe

Tendances

Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpELEldad Dor
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJosé Paumard
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Groupbaroquebobcat
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...Fwdays
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracerrahulrevo
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections LibraryPaul Phillips
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 

Tendances (20)

Spring has got me under it’s SpEL
Spring has got me under it’s SpELSpring has got me under it’s SpEL
Spring has got me under it’s SpEL
 
JDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easyJDK8 : parallel programming made (too ?) easy
JDK8 : parallel programming made (too ?) easy
 
Mirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby GroupMirah Talk for Boulder Ruby Group
Mirah Talk for Boulder Ruby Group
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Coffee script
Coffee scriptCoffee script
Coffee script
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
All about scala
All about scalaAll about scala
All about scala
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Building a java tracer
Building a java tracerBuilding a java tracer
Building a java tracer
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
A Scala Corrections Library
A Scala Corrections LibraryA Scala Corrections Library
A Scala Corrections Library
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Beyond java8
Beyond java8Beyond java8
Beyond java8
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 

En vedette

The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)Peter Eisentraut
 
Around "Hello World" in 30 Days
Around "Hello World" in 30 DaysAround "Hello World" in 30 Days
Around "Hello World" in 30 DaysDavid Eisinger
 
Liftweb
LiftwebLiftweb
LiftwebScalac
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scalafanf42
 
Testing practicies not only in scala
Testing practicies not only in scalaTesting practicies not only in scala
Testing practicies not only in scalaPaweł Panasewicz
 
MySQL Monitoring Shoot Out
MySQL Monitoring Shoot OutMySQL Monitoring Shoot Out
MySQL Monitoring Shoot OutKris Buytaert
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?Alex Payne
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkRahul Jain
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 

En vedette (17)

Java to scala
Java to scalaJava to scala
Java to scala
 
The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)The Common Debian Build System (CDBS)
The Common Debian Build System (CDBS)
 
Scala Sjug 09
Scala Sjug 09Scala Sjug 09
Scala Sjug 09
 
Around "Hello World" in 30 Days
Around "Hello World" in 30 DaysAround "Hello World" in 30 Days
Around "Hello World" in 30 Days
 
Liftweb
LiftwebLiftweb
Liftweb
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Testing practicies not only in scala
Testing practicies not only in scalaTesting practicies not only in scala
Testing practicies not only in scala
 
Scala-Ls1
Scala-Ls1Scala-Ls1
Scala-Ls1
 
MySQL Monitoring Shoot Out
MySQL Monitoring Shoot OutMySQL Monitoring Shoot Out
MySQL Monitoring Shoot Out
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?
 
MySQL DBA
MySQL DBAMySQL DBA
MySQL DBA
 
Scala
ScalaScala
Scala
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Scala Days NYC 2016
Scala Days NYC 2016Scala Days NYC 2016
Scala Days NYC 2016
 
Real time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache SparkReal time Analytics with Apache Kafka and Apache Spark
Real time Analytics with Apache Kafka and Apache Spark
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 

Similaire à Scala 3camp 2011

Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertextfrankieroberto
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicTimothy Perrett
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Raffi Krikorian
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009Michael Neale
 
What you forgot from your Computer Science Degree
What you forgot from your Computer Science DegreeWhat you forgot from your Computer Science Degree
What you forgot from your Computer Science DegreeStephen Darlington
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Falcon初印象
Falcon初印象Falcon初印象
Falcon初印象勇浩 赖
 

Similaire à Scala 3camp 2011 (20)

Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Fantom and Tales
Fantom and TalesFantom and Tales
Fantom and Tales
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Groovy
GroovyGroovy
Groovy
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Scala en
Scala enScala en
Scala en
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
 
Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....Scala + WattzOn, sitting in a tree....
Scala + WattzOn, sitting in a tree....
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009
 
What you forgot from your Computer Science Degree
What you forgot from your Computer Science DegreeWhat you forgot from your Computer Science Degree
What you forgot from your Computer Science Degree
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
Dartprogramming
DartprogrammingDartprogramming
Dartprogramming
 
Cpp tutorial
Cpp tutorialCpp tutorial
Cpp tutorial
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Introduction to JQuery
Introduction to JQueryIntroduction to JQuery
Introduction to JQuery
 
Falcon初印象
Falcon初印象Falcon初印象
Falcon初印象
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 

Plus de Scalac

Applicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaApplicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaScalac
 
AWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccAWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccScalac
 
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Scalac
 
React Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacReact Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacScalac
 
Introduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacIntroduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacScalac
 
ZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół ScalacZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół ScalacScalac
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Scalac
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Scalac
 
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacHow to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacScalac
 
Do you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacDo you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacScalac
 
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacCan we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacScalac
 
How to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńHow to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńScalac
 
ActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećScalac
 

Plus de Scalac (13)

Applicative functors by Łukasz Marchewka
Applicative functors by Łukasz MarchewkaApplicative functors by Łukasz Marchewka
Applicative functors by Łukasz Marchewka
 
AWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka ScalaccAWS Api Gateway by Łukasz Marchewka Scalacc
AWS Api Gateway by Łukasz Marchewka Scalacc
 
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
Do ECTL not ETL: the art and science of data cleansing in data pipelines by P...
 
React Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv ScalacReact Hooks by Oleksandr Oleksiv Scalac
React Hooks by Oleksandr Oleksiv Scalac
 
Introduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski ScalacIntroduction to Scala by Piotr Wiśniowski Scalac
Introduction to Scala by Piotr Wiśniowski Scalac
 
ZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół ScalacZIO actors by Mateusz Sokół Scalac
ZIO actors by Mateusz Sokół Scalac
 
Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...Why functional programming and category theory strongly matters - Piotr Parad...
Why functional programming and category theory strongly matters - Piotr Parad...
 
Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...Big picture of category theory in scala with deep dive into contravariant and...
Big picture of category theory in scala with deep dive into contravariant and...
 
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski ScalacHow to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
How to write automated tests and don’t lose your mind by Dorian Sarnowski Scalac
 
Do you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych ScalacDo you have that Spark in your ECTL? by Piotr Sych Scalac
Do you have that Spark in your ECTL? by Piotr Sych Scalac
 
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski ScalacCan we automate the process of backlog prioritizing? by Adam Gadomski Scalac
Can we automate the process of backlog prioritizing? by Adam Gadomski Scalac
 
How to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej GreńHow to create the right sales funnel for your business? by Maciej Greń
How to create the right sales funnel for your business? by Maciej Greń
 
ActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej KopećActorRef[Typed] by Andrzej Kopeć
ActorRef[Typed] by Andrzej Kopeć
 

Scala 3camp 2011

  • 1. Scala the next … ? ŁukaszKuczera
  • 3. PHP
  • 5. Scala Hybrid Object-Functional With type inferention Duck typing And multiple inheritance Compiles to JVM and CLR
  • 8. 1995 Well no but, lets do some functional programming in Java !! Have you seen Martin this Java thing that “runs everywhere” ?
  • 10. Martin Odersky GiladBracha PhillWadler David Stoutamire Scala Newspeak Haskell
  • 11.
  • 13. Scala bread and butter
  • 14. IDE Eclipse NetBeans IDEA Emacs Vim TextMate
  • 15. Enough of blabberingshow us the code !
  • 16. 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)) } }
  • 17. 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)
  • 18. 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 !
  • 19. Do not underestimate the power of Scala !
  • 20. 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
  • 22. DSL
  • 23. 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) }
  • 24. 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 } }
  • 25. 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('')")
  • 26. 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; } }
  • 27. Class Parameters - Scala classPerson(var name: String,var age:Int)
  • 28. 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); } } }
  • 29. Partition - Scala valall = Array[Person]() val(minors, adults)=all.partition(_.age < 18)
  • 30. Reduce - Java classReduce{ List<Person>all; intsum=0; for(Personp: all){ sum+=p.getAge(); } }
  • 31. Reduce - Scala valall = Array[Person]() all.map(_.age).reduce(_+_)
  • 32. 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); }
  • 33. Sort - Scala valall = Array[Person]() all.sortBy(_.age)
  • 34. 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
  • 35. 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)
  • 36. 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
  • 37. 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)
  • 38. 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)
  • 39. XML val person =<personname="ŁukaszKuczera"> <addressvoivodeship="Pomorskie"> <city>Gdańsk</city> </address> </person> valname = person quot;@name” valaddress = person quot;address" valcity = address quot;city” val_city = person "city"
  • 40. 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) })
  • 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).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 })
  • 42. 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
  • 43. 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")
  • 44. Who uses Scala already
  • 45. If I where to choose language other than Java it would be Scala
  • 46. „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”
  • 47. „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”
  • 48. 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)
  • 49. Join me and together we will rule the galaxy !
  • 50. About Me l.kuczera@jextreme.pl lkuczera http://acidbits.org/blog http://github.com/lkuczera/lift-blog

Notes de l'éditeur

  1. Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  2. Skalujesię do potrzeb I umiejętnościObiektowość – dobra do tworzeniaabstrakcji, dużychsystemówFunkcyjność – dobra w małejskali
  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. David pollackMesa spreadsheet
  6. David pollackMesa spreadsheet
  7. David pollackMesa spreadsheet
  8. David pollackMesa spreadsheet
  9. Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  10. Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  11. Wszystko jestobiektem, braktypówprymitywnychNie ma operatorów – wszystko jest wywołaniemmetod
  12. Pozwalanarozszerzanieistniejącychklas
  13. Pozwalanarozszerzanieistniejącychklasbezkoniecznościzmian
  14. W czym to jest napisane ?
  15. Obie formysąrównoznaczne
  16. dfasdfadfladkj