Getting Started With Scala


Published on

This presentation was presented at OSS camp in New Delhi. It deals with the basics of Scala language and how we can use it to build scalable Applications

Published in: Technology

Getting Started With Scala

  1. 1. Getting Started with Scala Vikas Hazrati - Meetu Maltiar - OSScamp Delhi 2009
  2. 2. AgendaI. What is FP and OOP? I. Features – Quick comparison with JavaI. Introducing Scala – Function Values and Closures – Scalable Languages – Traits – Scala is a Scripting language – Pattern Matching – Scala is Java of future I. End Notes – Scala is OO - Who is using it ? – Scala is Interoperable - Tool support - Learning resources
  3. 3. I. What is FP and OOP?
  4. 4. What is FPIs a concept where you can pass functions as arguments, to store them in variables, and to return them from other functions.
  5. 5. What is OOP?Object Oriented Programming is programming which is oriented around objectsTakes advantage of Encapsulation, Polymorphism, and Inheritance to increase code reuse and decrease code maintenance.
  6. 6. Scala: FP and OOP languageScala is a object oriented and functional programming language which is completely interoperable with javaFP: Makes it easy to build interesting things from simple parts, using – Higher order functions – Algebraic types and pattern matching – Parametric polymorphismOOP: Makes it easy to adopt and extend complex systems using – Subtyping and inheritance – Dynamic configurations – Classes as partial abstractions
  7. 7. II. Introducing Scala
  8. 8. Scalable languagesA language is scalable if it is suitable for very small as well as very large programs.A single language for extension scripts and the heavy lifting.Application-specific needs are handled through libraries and embedded DSLs instead of external languages.Scala shows that this is possible. 8
  9. 9. Scala is a scripting languageIt has an interactive read-eval-print-loop (REPL).Types can be inferred.Boilerplate is scrapped.scala> var capital = Map("US" → "Washington", "France" → "Paris")capital: Map[String, String] = Map(US → Washington, France →Paris)scala> capital += ("Japan" → "Tokyo")scala> capital("France")res7: String = Paris 9
  10. 10. Scala is the Java of the futureIt has basically everything Java has now. (sometimes in different form)It has closures. (proposed for Java 7, but rejected)It has traits and pattern matching. (do not be surprised to see them in Java 8, 9 or 10)It compiles to .class files, is completely interoperable and runs about as fast as Java object App { def main(args: Array[String]) { if (args exists (_.toLowerCase == "-help")) printUsage() else process(args) } } 10
  11. 11. Scala is object-orientedEvery value is an objectEvery operation is a method callExceptions to these rules in Java (such as primitive types, statics) are eliminated. scala> (1).hashCode res8: Int = 1 scala> (1).+(2) res10: Int = 3 11
  12. 12. InteroperabilityScala fits seamlessly into a Java environmentCan call Java methods, select Java fields, inherit Java classes, implement Java interfaces, etc.None of this requires glue code or interface descriptionsJava code can also easily call into Scala codeScala code resembling Java is translated into virtually the same bytecodes. ⇒ Performance is usually on a par with Java 12
  13. 13. III. Scala Features 13
  14. 14. Scala compared to JavaScala adds Scala removes+ a pure object system - static members+ operator overloading - primitive types+ closures - break, continue+ mixin composition with - special treatment oftraits interfaces+ existential types - wildcards+ abstract types - raw types+ pattern matching - enums 14
  15. 15. Scala cheat sheet (1): DefinitionsScala method definitions: Java method definition:def fun(x: Int): Int = { int fun(int x) { result return result } }def fun = result (no parameterless methods)Scala variable definitions: Java variable definitions:var x: Int = expression int x = expressionval x: String = expression final String x = expression 15
  16. 16. Scala cheat sheet (2): Objects and ClassesScala Class and Object Java Class with statics class Sample { class Sample(x: Int, val p: Int) { private final int x; def instMeth(y: Int) = x + y public final int p; } Sample(int x, int p) { this.x = x; this.p = p; object Sample { } def staticMeth(x: Int, y: Int) int instMeth(int y) { = return x + y; x*y } } static int staticMeth(int x, int y) { return x * y; } } 16
  17. 17. Scala cheat sheet (3): TraitsScala Trait Java Interface trait T { interface T { def abstractMth(x: String): Int int abstractMth(String x) def concreteMth(x: String) = } x + field (no concrete methods) var field = “!” (no fields)} Java extension + implementation:Scala mixin composition: class C extends Super class C extends Super with T implements T 17
  18. 18. Scala Compared to Java class CreditCard(val number: Int, var creditLimit: Int) javap -private CreditCardpublic class CreditCard extends java.lang.Object implementsscala.ScalaObject{ private int creditLimit; private final int number; public CreditCard(int, int); public void creditLimit_$eq(int); public int creditLimit(); public int number(); public int $tag() throws java.rmi.RemoteException;} 18
  19. 19. Constructorsclass Person(val firstName: String, val lastName: String) { private var position: String = _ println("Creating " + toString()) def this (firstName: String, lastName: String, positionHeld: String) { this (firstName, lastName) position = positionHeld } override def toString() : String = { firstName + " " + lastName + " holds " + position + " position " }} 19
  20. 20. Statics in Scala 20
  21. 21. Higher Order Functions 21
  22. 22. Currying & Partial FunctionsCurrying in Scala transforms a function that takes more than oneparameter into a function that takes multiple parameter lists. 22
  23. 23. ClosuresYou can create code blocks with variables that are not bound.You will have to bind them before you can invoke the function; however,they could bind to, or close over, variables outside of their local scopeand parameter list.That’s why they’re called closures. 23
  24. 24. Closures 24
  25. 25. TraitsThey are fundamental unit for code reuse in ScalaA Trait encapsulates method and field definitions, which can be reused by mixing them in classesUnlike class inheritance , in which class must inherit from just one superclass, a class may mix in any number of TraitsUnlike Interfaces they can have concrete methods 25
  26. 26. Traitstrait Philosophical { def philosophize() { println("I consume memory, therefore I am!") }}class Frog extends Philosophical {override def toString() = "green"}val latestFrog = new Frogprintln("" + latestFrog)latestFrog.philosophize()val phil:Philosophical = latestFrogphil.philosophize() 26
  27. 27. Pattern MatchingAll that is required is to add a single case keyword to each class that is to be pattern matchableSimilar to switch expect that Scala compares Objects as expressions 27
  28. 28. Pattern Matchingobject PatternApplication { def main(args : Array[String]) : Unit = { println( simplifyTop(UnOperator("-", UnOperator("-", Variable("x"))))) println( simplifyTop(BinOperator("+", Variable("x"), NumberOperator(0)))) println( simplifyTop(BinOperator("*", Variable("x"), NumberOperator(1)))) } def simplifyTop(expr: Expression): Expression = expr match { case UnOperator("-", UnOperator("-", e)) => e // Double negation case BinOperator("+", e, NumberOperator(0)) => e // Adding zero case BinOperator("*", e, NumberOperator(1)) => e // Multiplying by one case _ => expr}} 28
  29. 29. IV. End Notes 29
  30. 30. Tool support – Standalone compiler: scalac – Fast background compiler: fsc – Interactive interpreter shell and script runner: scala – Web framework: lift – Testing frameworks: Specs, ScalaCheck, ScalaTest, SUnit, …IDE plugins for: – Eclipse (supported by EDF) – IntelliJ (supported by JetBrains) – Netbeans (supported by Sun) 30
  31. 31. Who’s using it?Open source projects: lift wicket NetLogo SPDE: Scala branch for Processing Isabelle: GUI and code extractorCompanies: Twitter: infrastructure Sony Pictures: middleware infrastructure SAP community: ESME company messaging Reaktor: many different projects Mimesis Republic: multiplayer games EDF: trading, … 31
  32. 32. Learning ScalaTo get started:First steps in Scala, by Bill Venners published in Scalazine at www.artima.comScala for Java Refugees by Daniel Spiewack (great blog series)To continue:Programming in Scala, by Odersky, Spoon, Venners, published by Artima,comOther books are in the pipeline. 32
  33. 33. 33
  34. 34. Contact UsVikas Hazrati - vhazrati@xebia.comMeetu Maltiar - 34
  35. 35. References“Programming in Scala” book by Martin Odersky, Lex Spoon and Bill VennersPresentation by Martin Odersky at FOSDEM 2009 book on Scala by oreilly for Scala Programming Community 35