Share
Embed
Transcript
38 slides
-
WHY SCALA? << spoiler alert >> | So ware Developer
| 2016 Bianca Tesila -
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 -
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) -
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. -
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 -
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. -
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 -
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 -
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 -
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. -
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 } -
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 > -
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). -
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) -
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 } -
STATIC TYPING AND EXPRESSIVENESS Type annotations on the right side
Type inference User-defined implicits -
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 -
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 -
[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; } } -
Immutable & Mutable Fields val for immutable fields var for
mutable fields scala> :javap p Rational Compiled from "<console>" public class Rational { private final int n; public int n(); } scala> :javap p Rational Compiled from "<console>" public class Rational { private int n; public int n(); public void n_$eq(int); } -
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 } -
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) } } -
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) } } -
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) -
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 -
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? -
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 -
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 } -
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 } -
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!”) } } -
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!”) } -
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) -
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 -
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 -
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 -
WHERE TO GO FROM HERE... Programming in Scala 2nd Edition
Scala in Depth Functional Programming Principles in Scala Scala exercises -
Q & A Thank you for listening Email @ Bianca
Tesila Follow on Twitter biancatesila