Introducing scala


Published on

This presentation was presented as knowledge session at Knoldus. It is meant for Java professionals to quick-start them in Scala.

Published in: Technology
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Introducing scala

  1. 1. Introducing Scala Meetu Maltiar Principal Consultant Knoldus
  2. 2. AgendaStarting a Scala projectScala as a languageScala CollectionsScala Test
  3. 3. SBTBuild tool for Scala based projectsScala based frameworks like Akka uses itSBT build definition uses scala based DSLIncremental compilationWorks with mixed Scala and Java based projects
  4. 4. SBT: Lets create a projectSBT Installation download jar and create a scriptInstructions: xsbt wikiDescend in directory where you wanna create the projectIn terminal type sbtOnce the sbt is started enter following commandsset name := “ScalaKnolx”set version := “1.0”set scalaVersion := “2.9.1”session saveexitOpen build.sbt and have a look!!
  5. 5. SBT: Eclipse IDEAdd Typesafe repo and sbteclipse pluginIn build.sbtresolvers += "Typesafe Repository" at ""libraryDependencies += "org.scalatest" %% "scalatest" % "1.6.1"libraryDependencies += "junit" % "junit" % "4.9"Create project/plugins.sbt and add sbteclipse pluginaddSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.0.0")Execute sbt eclipseIt will generate eclipse related configs and now we are ready to importthis project in eclipse!!
  6. 6. Scala IntroductionScala is a JVM based languageScala combines FP and OO which makes it a scalable languageScala has a REPLScala is interoperable with Java
  7. 7. Scala is a scripting languageIt has a REPL.Types can be inferredLess BoilerplateScala> var capital = Map(“US” → “Washington”, “France” → “Paris”)Capital: Map[String, String] = Map(US-> Washington, France->Paris)Scala> capital += (“japan” → “Tokyo”)Scala> capital(“France”)Res2: String = Paris
  8. 8. Scala is OOEvery value is an objectEvery operation is method callExceptions to this in java like statics and primitives are removedScala> (1).hashCodeRes1: Int = 1Scala> (1).+(2)Res2: Int = 3
  9. 9. Scala compared to JavaScala adds Scala removes+ pure object system - static members+ operator overloading - primitive types+ closures - break, continue+ mixin composition with traits - special treatment of interfaces+ existential types - wildcards+ abstract types - raw types+ pattern matching - enums
  10. 10. Scala cheat sheet (1): Definitions Scala method definitions Java method definitions def fun(x: 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 = expression val x: String = expression final String x = expression
  11. 11. Scala cheat sheet (2): Definitions Scala Class and Object Java method definitions class Sample(x: Int, p: Int) { class Sample { def instMeth(y: Int): Int = x + y private final int x; } public final int p; object Sample { Sample(int x, int p) { def staticMeth(x: Int, y: Int): Int = x * y this.x = x; } this.p = p; } int instMeth(int y) { return x + y; } static int staticMeth(int x, int y) { return x * y; } }
  12. 12. Scala cheat sheet (3): TraitsScala Trait Java Interfacetrait T { Interface T {var field = “!” Int abstractMth(String x) }def abstractMth(x: Int): Int (no concrete methods)def concMth(x: String) = x + field (no fields)}Scala mixin composition Java extension plus implementationclass C extends Super with T class C extends Super implements T
  13. 13. Scala HOFScala is also FP along-with OOThis means that Function is also an ObjectThey can be passed along as objectsprivate def higherOrderFunction(f: Int => Int, x:Int): Int = { f(x) + 1 }
  14. 14. Scala Pattern MatchAll that is required is to add case keyword to each class that is tobe pattern matchableSimilar to switch except that Scala compares objects asexpressions getInteger(4) match { case 4 => println("four") case _ => println("not four") } def getInteger(x: Int): Int = { x }
  15. 15. Scala TraitsThey are fundamental unit of code reuse in ScalaThey encapsulates method and field definitions, which can bereused by mixing them in classesUnlike class inheritance a class can mix any number of traitsUnlike Interfaces they can have concrete methods
  16. 16. Scala CollectionsClass Person(val name: String, age: Int)val people: Array[Person]val(minors, adults) = people partition (_.age < 18)Three concepts: - pattern mach - infix method call - a function value
  17. 17. Scala way of CollectionsDe-emphasize destructive updatesFocus on transformers that map collections to collectionsHave complete range of persistent collections
  18. 18. Collection PropertiesObject-OrientedGeneric: List[T], Map[K, V]Optionally persistent: scala.collections.immutableHigher order: methods like foreach, map, filterUniform return type principle: operations return sametype as their left operand
  19. 19. Uniform Return Type Principlescala> val ys = List(1,2,3)ys: List[Int] = List(1,2,3)scala> val xs: Seq[Int] = ysxs: Seq[Int] = List(1,2,3)scala> xs map(_ + 1)res0: Seq[Int] = List(2,3,4)scala> ys map(_ + 1)res1: List[Int] = List(2,3,4)
  20. 20. Using Collections: Map and Filterscala> val xs = List(1,2,3)xs: List[Int] = List(1,2,3)scala> val ys = xs map (x => x + 1)xs: List[Int] = List(2,3,4)scala> val ys = xs map(_ + 1)ys: List[Int] = List(2,3,4)scala> val zs = ys filter (_ % 2 == 0)zs: List[Int] = List(2,4)scala> val as = ys map (0 to _)as: List[scala.collection.immutable.Range.Inclusive] =List(Range(0,1), Range(0,1,2), Range(0,1,2,3))
  21. 21. Using Collections: flatMap and groupByscala> val bs = as.flattenbs: List[Int] = List(0,1,0,1,2,0,1,2,3)scala> val bs = ys flatMap(0 to _)bs: List[Int] = List(0,1,0,1,2,0,1,2,3)scala> val fruit = Vector(“apples”, “oranges”, “ananas”)fruit: scala.collection.immutable.Vector[java.lang.String] =Vector(“apples”, “oranges”, “ananas”)scala> fruit groupBy (_.head)res2: scala.collection.immutable.Map[char,scala.collection.immutable.Vector[java.lang.String]] = Map(a->Vector(apples, ananas), o -> Vector(oranges))
  22. 22. Using Collections: for notationscala> for(x ← xs) yield x + 1 // mapres0: Seq[Int] = List(2,3,4)scala> for(x ← res0 if x % 2 == 0) yield x // filterres1: Seq[Int] = List(2,4)scala> for(x ← xs; y ← 0 to x) yield y // flatMapres2: Seq[Int] = List(0, 1, 0, 1, 2, 0, 1, 2, 3)
  23. 23. String also a collectionEven String is a collection that means that we can apply higherorder functions on itscala> val aString = “hello world”aString: java.lang.String = hello worldscala> aString map (_.toUpper)res1: String = HELLO WORLD
  24. 24. Using Mapsscala> val m = Map(1 → “ABC”, 2 → “DEF”, 3 → “GHI”)m: scala.collection.immutable.Map[Int, java.lang.String] = Map(1 →ABC, 2 → DEF, 3 → GHI)scala> m(2)res1: java.lang.String = DEFscala> m + (4 → “JKL”)res2: scala.collection.immutable.Map[Int, java.lang.String] = Map(1→ ABC, 2 → DEF, 3 → GHI, 4 → JKL)scala> m map {case (k, v) => (v, k)}res2: scala.collection.immutable.Map[java.lang.String, Int] =Map(ABC → 1, DEF → 2, GHI → 3)
  25. 25. Scala Collection HierarchyAll collection classes are in scala.collection or one of its sub-packages mutable, immutable and genericRoot collections are in scala.collection define same interface asimmutable collections and mutable collections add somemodification operations to make it mutableThe generic package contains building block for implementingcollections
  26. 26. Scala.Collection Hierarchy
  27. 27. Scala.Collection.Immutable
  28. 28. Overview of Collections
  29. 29. Commonality In CollectionsAll classes are quite common. For instance every collection can becreated by same uniform syntax Set(1, 2, 3) Seq(1, 2, 3) Traversable(1, 2, 3) Map(“x” → 24, “y” → 25)Applies with specific collection implementations List(1, 2, 3) HashMap(“x” → 24, “y” → 25)All these collections get displayed with toString in same way
  30. 30. Trait TraversableTop of Collection Hierarchy. Its abstract method is foreach:def foreach[U](f: Elem => U)Traversable also provides lot of concrete methods they fall in followingcategories
  31. 31. Everything is a libraryCollections feel that they are language constructsLanguage does not contain any collection related constructs - no collection types - no collection literals - no collection operatorsEverything is in libraryThey are extensible
  32. 32. Scala TestScala Test is an open source framework for Java platformWith ScalaTest we can test either Scala or Java codeIntegrates with popular tools like jUnit, TestNG, Ant, Maven and SBTDesigned to do different styles of testing like Behavior Driven Design forexample
  33. 33. Scala Test ConceptsThree concepts:Suite: A collection of tests. A test is anything which has a name and cansucceed or failRunner: ScalaTest provides a runner application and can run a suite oftestsReporter: As the tests are run, events are fired to reporter, it takes careof presenting results back to user
  34. 34. Scala Test Is Customizable Suite <<trait>> def expectedTestCount(Filter: Int) def testNames: Set[String] def tags: Map[String, Set[String]] def nestedSuites: List[Suite] def run(Option[String], Reporter, …) def runNestedSuites(Reporter, …) def runTests(Option[String]), Reporter def runTest(Reporter, …) def withFixture(NoArgTest)
  35. 35. Scala Test: under the hoodWhen you run a Test in Scala Test you basically invokerun(Option[String], Reporter, …) on Suite objectIt then calls runNestedSuites(Reporter, …)And it calls runTests(Option[String], Reporter, …)runNestedSuites(Reporter, …):Invokes nestedSuites(): List[Suite] to get a list of nested suitesrunTests(Option[String], Reporter, …) will call def testNames:Set[String] to get set of test names to run. For each test it callsrunTest(Reporter, …) It wraps the test code as a Function object with aname and passes it to the withFixture(NoArgTest) which actually runs thetest
  36. 36. Pick a core Trait
  37. 37. Mixin other Traits
  38. 38. Scala Test: Available TraitsSuiteFunSuiteSpecFlatSpecWordSpecFeatureSpecAssertionsShouldMatchersMustMatchers
  39. 39. SuiteTraits approach to writing tests. Create classes extending Suiteand define test methodsTest methods have names testXXXX. All methods must be publicScala Test provides === operator. It is defined in Trait Assertions.Allows the failure report to include both right and left values
  40. 40. FunSuiteFor writing Functional Tests use FunSuite Fun => functional“test” is a method defined in FunSuite Trait. Test name goes inparentheses and test body goes in curly bracesThe test code in curly braces is passed as a by-name parameter to“test” method which registers for later execution
  41. 41. AssignmentLets map the world. We have Continents and CountriesMake a Collection hierarchy to hold the above informationWrite method on the collection hierarchy to get countries of acontinentWrite method on the collection hierarchy to get continent for acountryWrite tests using FunSuite to test the methods created above