Upload
lukasz-kuczera
View
1.029
Download
2
Embed Size (px)
DESCRIPTION
Scala presentation for 3camp June 2011
Citation preview
Scala the next … ?
Łukasz Kuczera
Java
PHP
Python
Scala
Hybrid Object-Functional
With type inferention
Duck typing
And multiple inheritance
Compiles to JVM and CLR
Scalable
History
1995
Have you seen Martin this Java thing that “runs everywhere” ?
Well no but, lets do some functional programming in
Java !!
Pizza
Phill WadlerMartin Odersky Gilad Bracha
David Stoutamire
HaskellNewspeakScala
Funnel – 1999Scala – 2003
Scala bread and butter
IDE
Eclipse NetBeans IDEA Emacs Vim TextMate
Enough of blabberingshow us the code !
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)) }}
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)
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 !
Do not underestimate the power of
Scala !
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
Pimp my library pattern
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 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 }}
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('')")
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;}
}
Class Parameters - Scala class Person(var name: String, var age: Int)
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);
}}
}
Partition - Scala val all = Array[Person]() val (minors, adults) = all.partition(_.age < 18)
Reduce - Javaclass Reduce {
List<Person> all;int sum = 0;for(Person p: all) {
sum += p.getAge();}
}
Reduce - Scala val all = Array[Person]() all.map(_.age).reduce(_ + _)
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);
}
Sort - Scala val all = Array[Person]() all.sortBy(_.age)
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
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)
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
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)
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)
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"
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)})
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 })
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
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")
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 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)
Join me and together we will rule the galaxy !