50
Scala the next … ? Łukasz Kuczera

Scala 3camp 2011

Embed Size (px)

DESCRIPTION

Scala presentation for 3camp June 2011

Citation preview

Page 1: Scala   3camp 2011

Scala the next … ?

Łukasz Kuczera

Page 2: Scala   3camp 2011

Java

Page 3: Scala   3camp 2011

PHP

Page 4: Scala   3camp 2011

Python

Page 5: Scala   3camp 2011

Scala

Hybrid Object-Functional

With type inferention

Duck typing

And multiple inheritance

Compiles to JVM and CLR

Page 6: Scala   3camp 2011

Scalable

Page 7: Scala   3camp 2011

History

Page 8: Scala   3camp 2011

1995

Have you seen Martin this Java thing that “runs everywhere” ?

Well no but, lets do some functional programming in

Java !!

Page 9: Scala   3camp 2011

Pizza

Page 10: Scala   3camp 2011

Phill WadlerMartin Odersky Gilad Bracha

David Stoutamire

HaskellNewspeakScala

Page 11: Scala   3camp 2011
Page 12: Scala   3camp 2011

Funnel – 1999Scala – 2003

Page 13: Scala   3camp 2011

Scala bread and butter

Page 14: Scala   3camp 2011

IDE

Eclipse NetBeans IDEA Emacs Vim TextMate

Page 15: Scala   3camp 2011

Enough of blabberingshow us the code !

Page 16: Scala   3camp 2011

class Test { // variable definition var n: Int = 5 // value definition val i = 10 // function definition def sum(i: Int, n: Int): Int = i+n

def printit(x: Any) = println(x) } object Basics extends Test { override val i = 20 override def sum(i: Int, n: Int): Int = i+n def main(args: Array[String]) { printit(sum(i,n)) }}

Page 17: Scala   3camp 2011

Objects and Operators 3 + 4 5 % 2 3 * 3

val test = new Test test printit "hello world !”

class OpOverloading { def +(x: Any) = println("I'm + function/operator") }

== 3.+(4)== 5.%(2)

== 3.*(3)

Page 18: Scala   3camp 2011

Rational Exampleclass Rational(val i: Int, val n: Int) { def this(i: Int) = this(i, 1) def * (other: Rational) = new Rational(i * other.i, n * other.n) override def toString = i +"/"+ n def * (other: Int) = new Rational(i * other, n)}

val third = 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 !

Page 19: Scala   3camp 2011

Do not underestimate the power of

Scala !

Page 20: Scala   3camp 2011

Implicit definitions unleashedclass Rational(val i: Int, val n: Int) { def this(i: Int) = this(i, 1) def * (other: Rational) = new Rational(i * other.i, n * other.n) override def toString = i +"/"+ n def * (other: Int) = new Rational(i * other, n)}

val third = 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 implicit def int2rational(i: Int) = new Rational(i) 3 * quarter // == 3/4

Page 21: Scala   3camp 2011

Pimp my library pattern

Page 22: Scala   3camp 2011

DSL

Page 23: Scala   3camp 2011

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)}

Page 24: Scala   3camp 2011

object Lunar extends Baysick { 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 "You are drifting towards the moon." 70 PRINT "You must decide how much fuel to burn." 80 PRINT "To accelerate enter a positive number" 90 PRINT "To decelerate 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 "You don't have that much 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 "You have hit the surface" 200 IF 'v < 3 THEN 240 210 PRINT "Hit surface too fast (" % 'v % ")km/s" 220 PRINT "You Crashed!" 230 GOTO 250 240 PRINT "Well done"

250 END RUN }}

Page 25: Scala   3camp 2011

And JavaScriptAppendHtml("comments", <xml:group> <div class={ 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('')")

Page 26: Scala   3camp 2011

Class Parameters - Javapublic class Person {

private String name;private int age;

public Person(String name, int age) {this.name = name;this.age = age;

}public String getName() {

return name;}public void setName(String name) {

this.name = name;}public int getAge() {

return age;}public void setAge(int age) {

this.age = age;}

}

Page 27: Scala   3camp 2011

Class Parameters - Scala class Person(var name: String, var age: Int)

Page 28: Scala   3camp 2011

Partition - Javaclass Partition {

List<Person> all;List<Person> adults = new ArrayList<Person>();List<Person> minors = new ArrayList<Person>();for(Person p: all) {

if(p.getAge()<18) {minors.add(p);

} else {adults.add(p);

}}

}

Page 29: Scala   3camp 2011

Partition - Scala val all = Array[Person]() val (minors, adults) = all.partition(_.age < 18)

Page 30: Scala   3camp 2011

Reduce - Javaclass Reduce {

List<Person> all;int sum = 0;for(Person p: all) {

sum += p.getAge();}

}

Page 31: Scala   3camp 2011

Reduce - Scala val all = Array[Person]() all.map(_.age).reduce(_ + _)

Page 32: Scala   3camp 2011

Sort - Javaclass Sort {

List<Person> all;Comparator<Person> comp = new

Comparator<Person>() {public int compare(p1: Person, p2: Person) {

return p1.getAge() - p2.getAge();}

};Collections.sort(all, comp);

}

Page 33: Scala   3camp 2011

Sort - Scala val all = Array[Person]() all.sortBy(_.age)

Page 34: Scala   3camp 2011

Objects as Functions val adder = (x: Int) => x + 1

val anonfun1 = new Function1[Int, Int] { def apply(x: Int): Int = x + 1 }

adder(1) // == 2 anonfun1(5) // == 6

Page 35: Scala   3camp 2011

Functions as Objects val adder = (x: Int) => x + 1 adder.apply(1) // == 2 adder.apply(5) // == 6

def higherOrderFunction(f: (Int => Int), x: Int) = f(x) higherOrderFunction(adder, 1)

Page 36: Scala   3camp 2011

Structural (Duck) Typing def doIn(resource: { def open(): Unit; def close(): Unit }) { resource.open(); // do some useful stuff ... resource.close(); }

val a = new ScalaObject { def open() {} def close() {} }

val b = new ScalaObject { def open() {}// def close() {} }

doIn(a) doIn(b) // compilation error

Page 37: Scala   3camp 2011

Multiple parameter lists def doIn(code: () => Unit)

(resource: { def open(): Unit; def close(): Unit }) { resource.open(); code() resource.close(); }

doIn(() => { // do some useful stuff ...

})(a) def myUsefulFunc() { // lots of lots of wonderful code .. }

doIn(myUsefulFunc)(a)

Page 38: Scala   3camp 2011

Implicit Parametersdef doIn(code: () => Unit) (implicit resource: { def open(): Unit; def close(): Unit }) { resource.open(); code() resource.close();}

implicit val a = new ScalaObject { def open() {} def close() {}}

doIn(() => { // do some useful stuff ...}) (a)

Page 39: Scala   3camp 2011

XML val person = <person name="Łukasz Kuczera"> <address voivodeship="Pomorskie"> <city>Gdańsk</city> </address> </person>val name = person \ "@name”val address = person \ "address" val city = address \ "city”val _city = person \\ "city"

Page 40: Scala   3camp 2011

val xml = <div class="rsswidget"> <ul> <li><a href="http://www.quotationspage.com/qotd.html">

Quotes of the Day</a></li> <li><a href="http://www.quotationspage.com/quotes/C._P._Snow">

C. P. Snow</a></li> <li><a href="http://www.quotationspage.com/quotes/

unknown">unknown</a></li> <li><a href="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)})

Page 41: Scala   3camp 2011

val xml = <div class="rsswidget"> <ul><li> <a href="http://www.quotationspage.com/qotd.html">Quotes of the Day</a></li> <li><a href="http://www.quotationspage.com/quotes/C._P._Snow">

C. P. Snow</a></li> <li><a href="http://www.quotationspage.com/quotes/unknown">unknown</a></li> <li><a href="http://www.quotationspage.com/quotes/Frederick_Locker- Lampson">Frederick Locker-Lampson</a></li> </ul> </div>

(xml \\ "@href").slice(1, 4).foreach(url => { val con = new URL(url.toString).openConnection val reader = new BufferedReader(new InputStreamReader(con.getInputStream,

"ISO-8859-1")) var line = ""; while (line != null) { line = reader.readLine if (line != null) println(line) } con.getInputStream.close })

Page 42: Scala   3camp 2011

Nulls - JavaMap<String, String> capitals =

new HashMap<String, String>();

capitals.put("Poland", "Warsaw");

System.out.println(capitals.get("Polska").trim());

Exception in thread "main" java.lang.NullPointerException

Page 43: Scala   3camp 2011

Nulls - Scala val capitals = Map("Poland" -> "Warsaw"); val capitalOption:Option[String] = capitals.get("Polska") capitalOption match { case Some(value) => println(value) case None => println("Not found") case _ => } if(capitalOption.isDefined) println(capitalOption.get) println(capitalOption getOrElse "Not found")

Page 44: Scala   3camp 2011

Who uses Scala already

Page 45: Scala   3camp 2011

If I where to choose language other thanJava it would be

Scala

Page 46: Scala   3camp 2011

„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”

Page 47: Scala   3camp 2011

„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”

Page 48: Scala   3camp 2011

Scala FeaturesType InferenceUniform Access PrincipleClosuresCuryingHigher Order FunctionsPattern MatchingActorsGenerics (covariance, higher order kinds)Native XML supportAbstract control structuresImplicit conversions and parametersAdvanced for expressionsAnnotationsCombinator parsingTraitsDuck typingNull „safety” (Option Type)

Page 49: Scala   3camp 2011

Join me and together we will rule the galaxy !

Page 50: Scala   3camp 2011

About Me

[email protected]

lkuczera

http://acidbits.org/blog

http://github.com/lkuczera/lift-blog