Slide 1

Slide 1 text

WHY SCALA? << spoiler alert >> | So ware Developer | 2016 Bianca Tesila

Slide 2

Slide 2 text

Agenda Introduction FP Features OOP Features Conclusion Q&A

Slide 3

Slide 3 text

A LITTLE HISTORY... Late 90s: Trying to make Java better - generics 2001: Decided to make a better Java 2003: First experimental release 2005: Scala 2.0

Slide 4

Slide 4 text

2011: Scala 2.9, Lightbend founded (ex. Typesafe) Today: Scala 2.11 SCALA Created with the goal of being a better general purpose language Inspired by the criticism of Java shortcomings Both Object Oriented and Functional Compiles into Java bytecode and runs on the JVM Interoperable with Java Very strong static type system (richer than Java's)

Slide 5

Slide 5 text

FUNCTIONAL Treats computations as an evaluation of mathematical functions and avoids state and mutable data. No mutable variables No assignments No imperative control structures Lisp / Closure / Haskell / Scheme / Scala etc.

Slide 6

Slide 6 text

WHY FUNCTIONAL? Managing state in multi-core is a nightmare Functional programming techniques are inherently parallelizable Allows compilers to perform optimizations Provider higher level abstractions

Slide 7

Slide 7 text

FUNCTIONAL MEETS OBJECT ORIENTATION Two different ways of looking at a problem: functions versus objects << In Scala, functions are objects. >> Programs can be constructed through both the definition and composition of objects and functions.

Slide 8

Slide 8 text

Object oriented programming Functional programming Composition of objects (nouns) Composition of functions (verbs) Encapsulated stateful interaction Deferred side effects Iterative algorithms Recursive algorithms Imperative flow Lazy evaluation N/A Pattern matching

Slide 9

Slide 9 text

FEATURES OF FP IN SCALA First class / Higher order functions Closures Currying Recursion - tail call optimizations Non-strict (lazy) evaluation Pattern matching Type inference Strong collection libraries

Slide 10

Slide 10 text

FUNCTIONS [1] Scala has first class functions - it treats functions as first class citizens. => higher order functions - can take other functions as arguments or return functions

Slide 11

Slide 11 text

FUNCTIONS [2] Functions as unnamed literals can be passed as values. val increment = (x: Int) => x + 1 A function literal is compiled into a class that, when instantiated at runtime, is a function value.

Slide 12

Slide 12 text

CLOSURES Closing the function literal by capturing the bindings of its free variables. Allows a function access to non-local variables when invoked outside its scope. def start(x: Int) = { def increment(y: Int) = { x + y } increment }

Slide 13

Slide 13 text

CURRYING A technique for partial function application. Allows the conversion of a function of multiple parameters into a chain of functions that accept one or more parameters. In Scala, any function of multiple parameters can be curried. scala> val multipleParams = (x: Int, y: Double, z: String) => x + y + z multipleParams: (Int, Double, String) => String = < function3 > scala> val separateParams = multipleParams.curried separateParams: Int => (Double => (String => String)) = < function1 >

Slide 14

Slide 14 text

RECURSION FP: iteration (looping) is accomplished via recursion. Recursive functions invoke themselves until a base case is reached. Scala performs tail call optimization by default (avoid maintaining a stack).

Slide 15

Slide 15 text

NON-STRICT (LAZY) EVALUATION call-by-need / call-by-name An evaluation strategy which delays the evaluation of an expression until its value is needed. Can lead to smaller memory footprint Can increase performance Allows building infinite data structures (i.e.: streams - tail is evaluated only on demand)

Slide 16

Slide 16 text

PATTERN MATCHING Perceive the constituents of a data structure as constituents of a pattern. Match expressions make manipulations of complex data structures convenient and expressive. expr match { case pattern01 => result01 //there is no fall through to the next alterna case pattern02 => result02 //match expressions return a value }

Slide 17

Slide 17 text

STATIC TYPING AND EXPRESSIVENESS Type annotations on the right side Type inference User-defined implicits

Slide 18

Slide 18 text

Features of OO in Scala Classes and Traits Fields keep state No static class members Methods provide operations Access modifiers declare visibility Singleton Objects as First-Class Objects Inheritance Single Inheritance Multiple: Mix-in as many traits as you want

Slide 19

Slide 19 text

The Simplest Class scala> class Rational defined class Rational scala> val rational = new Rational rational: Rational = Rational@9d15d35 scala> rational.toString res0: String = Rational@9d15d35

Slide 20

Slide 20 text

[Spoiler] case class Rational(n: Int, d: Int public class Rational { public final int n; public final int d; public Rational(int n, int d) this.n = n; this.d = d; } }

Slide 21

Slide 21 text

Immutable & Mutable Fields val for immutable fields var for mutable fields scala> :javap ­p Rational Compiled from "" public class Rational { private final int n; public int n(); } scala> :javap ­p Rational Compiled from "" public class Rational { private int n; public int n(); public void n_$eq(int); }

Slide 22

Slide 22 text

Primary Constructors Similar to Java's default no-args constructor Spans the complete class definition Signature: name & parameters Implementation: body except for method definitions class Rational { val n: Int = 0 }

Slide 23

Slide 23 text

Class Parameters Class parameters are just constructor parameters They cannot be accessed from outside class Rational(n: Int, d: Int) { def add(that: Rational): Rational = { new Rational(n * that.d + that.n * d, d * that.d) } }

Slide 24

Slide 24 text

Class Parameters vs. Fields Class parameters may be promoted to fields by adding val or var before them class Rational(val n: Int, val d: Int) { def add(that: Rational) = { new Rational(n * that.d, d * that.n, d * that.d) } }

Slide 25

Slide 25 text

Methods Methods are class members providing operations Avoid using return - a Scala method/function returns the last expression evaluated Method/function parameters are vals (they cannot be reassigned)

Slide 26

Slide 26 text

Access Modifiers [1] All members are public by default Access is restricted using private Protected makes a member visible within its enclosing class and subclasses - more restrictive Access is relaxed up to a given entity by using a qualifier The strictest restriction can be achieved using the this qualifier

Slide 27

Slide 27 text

Access Modifiers (2) class Hello { private[this] val message = "Hello!" def messagesEqual(that: Hello) = this.message == that.message } Is there something wrong with the code?

Slide 28

Slide 28 text

Singleton Objects Scala classes can't have static members Singletons are first-class objects replacing static (e.g. holding constants) Use the object keyword to define a singleton object object Rational { val denominator = 1 } scala> Rational.denominator res0: Int = 1

Slide 29

Slide 29 text

Singleton Objects (2) If a singleton object and a class / trait share the same name, file & package, they are called companions Companions can access their private members - except for this, there is no relation at all class Rational (val n: Int, val d: Int) object Rational { val denominator = 1 }

Slide 30

Slide 30 text

Package Objects A package object provides code available at the package level Each package is allowed to have one package object Any definitions placed in a package object are considered members of the package itself; they can easily be imported by other members // numbers/package.scala package object numbers { val denominator = 1 }

Slide 31

Slide 31 text

A Scala Application A singleton object which doesn't share the same name with a companion class is called a standalone object Any standalone object with a main method of the proper signature can be used as the entry point into an application: object NumbersApp { def main(args: Array[String]) { println(“Hello, World!”) } }

Slide 32

Slide 32 text

A Simpler Scala Application Use scala.App if you don't want to define explicitly the main method To use this trait, write "extends App" a er the name of your singleton object The singleton object inherits the main method properly defined by App The code between the curly braces is collected into the primary constructor of the singleton object object NumbersApp extends App { println(“Hello, World!”) }

Slide 33

Slide 33 text

Case Classes case class Rational(nominator: Int, denominator: Int = 1) val one = Rational(1) one: Rational = Rational(1,1) No need for new to create new instances Nice implementations of toString, equals & hashCode Class params are promoted to immutable fields automatically copy method is automatically implemented Use case classes in pattern matching (see FP Features)

Slide 34

Slide 34 text

Case Classes (2) scala> Rational(1) res0: Rational = Rational(1,1) scala> Rational.apply(1) res1: Rational = Rational(1,1) Each case class has a companion object with an apply method The apply method is used as a factory method Calling apply works for any object

Slide 35

Slide 35 text

Why not only case classes? Overhead in byte code size Can not inherit a case class from another one Value objects are perfect candidates for case classes Service objects should not be case classes

Slide 36

Slide 36 text

WHY SCALA? 1. It's concise 2. It brings OO and Functional together 3. Interoperable with Java 4. Allows you to focus on what's important

Slide 37

Slide 37 text

WHERE TO GO FROM HERE... Programming in Scala 2nd Edition Scala in Depth Functional Programming Principles in Scala Scala exercises

Slide 38

Slide 38 text

Q & A Thank you for listening Email @ Bianca Tesila Follow on Twitter biancatesila