IN A JAVA 8 WORLD
FUNCTIONAL
OBJECT ORIENTED
JVM
BASED
WHY CHOOSE SCALA?
SCALA IS
SCALABL
E
All logos owned by respective companies.
Developers should start
thinking about tens, hundreds,
and thousands of cores now.”
- Intel
SCALABIT
Y IS
HARD
SIDE EFFECTS
public void setX(int x) {
this.x = x;
}
setX(0)
async { setX(getX() + 1) }
async { setX(getX() * 2) }
FUNCTIONAL PROGRAMING
PURE FUNCTIONS
def add1(x: Int) : Int = {
x + 1
}
val result = add1(1) + add1(2) // 5
val result = 2 + 3 // 5
FIRST CLASS FUNCTIONS
val hello = (name: String) => println(s"Hello $name”)
hello("Joe”)
Hello Joe
HIGH ORDER FUNCTIONS
HIGH ORDER FUNCTIONS
def greetings(name: String, f: String => String) = {
println(f(name))
}
val hello = (name: String) => s"Hello $name”
val hola = (name: String) => s"Hola $name”
greetings("Joe", hello)
Hello Joe
greetings("Joe", hola)
Hola Joe
ISN’T JAVA8
ENOUGH?
JAVA8 CAN
BE MADE
SCALABLE
IMMUTABLE CLASSES
public class ImmutablePoint {
private final int x;
private final int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
}
Java
Scala case class ImmutablePoint(x: Int, y: Int)
IMMUTABLE DATA STRUCTURES
Scala
List(1, 2)
Set(1, 2)
Map(("foo", 1), ("bar", 2))
List<Integer> uList = Arrays.asList(1, 2, 3);
Set<Integer> set = new HashSet<>();
set.add(1);
set.add(2);
Set<Integer> uSet = Collections.unmodifiableSet(set);
Map<String, Integer> map = new HashMap<>();
map.put("foo", 1);
map.put(”bar", 2);
Map<String, Integer> uMap = Collections.unmodifiableMap(map);
Java
SCALA IS EXPRESSIVE
TRAITS
trait WheelBarrow {
val capacity: Int = 20
def lift() = println("I need to go to the gym")
def roll() = println("Are we there yet")
def dump() = println("Go back for more")
}
trait Bench {
val occupancy: Int = 3
val color: String = "Red”
def sit() = println("Time to rest")
}
class BenchBarrow extends WheelBarrow with Bench
NAMED PARAMETERS
public class Person {
private String lastName = "Unknown";
private String firstName = "Unknown";
private String middleName = "Unknown";
private String salutation = "Unknown";
private String suffix = "Unknown";
public Person(String lastName, String firstName, String middleName,
String salutation, String suffix) {
this.lastName = lastName;
this.firstName = firstName;
this.middleName = middleName;
this.salutation = salutation;
this.suffix = suffix;
}
}
NAMED PARAMETERS
public class Person {
private final String lastName;
private final String firstName;
private final String middleName;
private final String salutation;
private final String suffix;
private Person(String lastName, String firstName, String middleName,
String salutation, String suffix) {
this.lastName = lastName;
this.firstName = firstName;
this.middleName = middleName;
this.salutation = salutation;
this.suffix = suffix;
}
public static class PersonBuilder {
private String lastName = "Unknown";
private String firstName = "Unknown";
private String middleName = "Unknown";
private String salutation = "Unknown";
private String suffix = "Unknown";
public PersonBuilder lastName(String newLastName) {
this.lastName = newLastName;
return this;
}
public PersonBuilder firstName(String newFirstName) {
this.firstName = newFirstName;
return this;
}
public PersonBuilder middleName(String newMiddleName) {
this.middleName = newMiddleName;
return this;
}
public PersonBuilder salutation(String newSalutation) {
this.salutation = newSalutation;
return this;
}
public PersonBuilder suffix(String newSuffix) {
this.suffix = newSuffix;
return this;
}
public Person build() {return new Person(lastName, firstName, middleName, salutation, suffix); }
}
}
NAMED PARAMETERS
case class Person(salutation: String = "Unknown", firstName: String = "Unknown",
middleName: String = "Unknown", lastName: String = "Unknown",
suffix: String = "Unknown")
Person("Mr", "John", "M", "Doe", "Sr")
Person(salutation = "Mr", firstName = "John", lastName = "Doe")
Person(firstName = "John", middleName = "M", lastName = "Doe")
Person(firstName = "John")
Person(lastName = "Doe")
Person(firstName = "John", lastName = "Doe")
PATTERN MATCHING
def parseArgument(arg: String, value: String)
PATTERN MATCHING
def parseArgument(arg: String, value: String) = (arg, value) match {
}
PATTERN MATCHING
def parseArgument(arg: String, value: String) = (arg, value) match {
case ("-h" | "--help", nil) => displayHelp()
}
PATTERN MATCHING
def parseArgument(arg: String, value: String) = (arg, value) match {
case ("-h" | "--help", nil) => displayHelp()
case ("-l" | "--log-level", level) => setLogLevel(level)
}
PATTERN MATCHING
def parseArgument(arg: String, value: String) = (arg, value) match {
case ("-h" | "--help", nil) => displayHelp()
case ("-l" | "--log-level", level) => setLogLevel(level)
case (bad, _) => badArgument(bad)
}
PATTERNS
// Constant patterns
case 0 => "zero”
case true => "true"
case "hello" => "you said hello”
// Data structure patterns
case List(0, _, _) => "a three-element list with 0 as the first element”
case List(1, _*) => "a list beginning with 1, having any number of elements”
// Constructor patterns
case Person(_,_,_,"Smith",_) => "found a Smith”
case Person(_,first,middle,"Smith",_) => s"found $first $middle Smith”
SCALA IS EXPRESSIVE
GETTING STARTED
• Functional Programming Principles in Scala
– coursera.com
• Introduction to Scala
– bigdatauniversity.com
• Scala Cookbook by Alvin Alexander
• Programming Scala by Dean Wampler & Alex Payne
QUESTIONS?

Scala in a Java 8 World

  • 1.
    IN A JAVA8 WORLD
  • 3.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
    All logos ownedby respective companies.
  • 10.
    Developers should start thinkingabout tens, hundreds, and thousands of cores now.” - Intel
  • 11.
  • 13.
    SIDE EFFECTS public voidsetX(int x) { this.x = x; } setX(0) async { setX(getX() + 1) } async { setX(getX() * 2) }
  • 14.
  • 16.
    PURE FUNCTIONS def add1(x:Int) : Int = { x + 1 } val result = add1(1) + add1(2) // 5 val result = 2 + 3 // 5
  • 18.
    FIRST CLASS FUNCTIONS valhello = (name: String) => println(s"Hello $name”) hello("Joe”) Hello Joe
  • 19.
  • 20.
    HIGH ORDER FUNCTIONS defgreetings(name: String, f: String => String) = { println(f(name)) } val hello = (name: String) => s"Hello $name” val hola = (name: String) => s"Hola $name” greetings("Joe", hello) Hello Joe greetings("Joe", hola) Hola Joe
  • 21.
  • 22.
  • 23.
    IMMUTABLE CLASSES public classImmutablePoint { private final int x; private final int y; public ImmutablePoint(int x, int y) { this.x = x; this.y = y; } public int getX() { return x; } public int getY() { return y; } } Java Scala case class ImmutablePoint(x: Int, y: Int)
  • 24.
    IMMUTABLE DATA STRUCTURES Scala List(1,2) Set(1, 2) Map(("foo", 1), ("bar", 2)) List<Integer> uList = Arrays.asList(1, 2, 3); Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); Set<Integer> uSet = Collections.unmodifiableSet(set); Map<String, Integer> map = new HashMap<>(); map.put("foo", 1); map.put(”bar", 2); Map<String, Integer> uMap = Collections.unmodifiableMap(map); Java
  • 25.
  • 27.
    TRAITS trait WheelBarrow { valcapacity: Int = 20 def lift() = println("I need to go to the gym") def roll() = println("Are we there yet") def dump() = println("Go back for more") } trait Bench { val occupancy: Int = 3 val color: String = "Red” def sit() = println("Time to rest") } class BenchBarrow extends WheelBarrow with Bench
  • 28.
    NAMED PARAMETERS public classPerson { private String lastName = "Unknown"; private String firstName = "Unknown"; private String middleName = "Unknown"; private String salutation = "Unknown"; private String suffix = "Unknown"; public Person(String lastName, String firstName, String middleName, String salutation, String suffix) { this.lastName = lastName; this.firstName = firstName; this.middleName = middleName; this.salutation = salutation; this.suffix = suffix; } }
  • 29.
    NAMED PARAMETERS public classPerson { private final String lastName; private final String firstName; private final String middleName; private final String salutation; private final String suffix; private Person(String lastName, String firstName, String middleName, String salutation, String suffix) { this.lastName = lastName; this.firstName = firstName; this.middleName = middleName; this.salutation = salutation; this.suffix = suffix; } public static class PersonBuilder { private String lastName = "Unknown"; private String firstName = "Unknown"; private String middleName = "Unknown"; private String salutation = "Unknown"; private String suffix = "Unknown"; public PersonBuilder lastName(String newLastName) { this.lastName = newLastName; return this; } public PersonBuilder firstName(String newFirstName) { this.firstName = newFirstName; return this; } public PersonBuilder middleName(String newMiddleName) { this.middleName = newMiddleName; return this; } public PersonBuilder salutation(String newSalutation) { this.salutation = newSalutation; return this; } public PersonBuilder suffix(String newSuffix) { this.suffix = newSuffix; return this; } public Person build() {return new Person(lastName, firstName, middleName, salutation, suffix); } } }
  • 30.
    NAMED PARAMETERS case classPerson(salutation: String = "Unknown", firstName: String = "Unknown", middleName: String = "Unknown", lastName: String = "Unknown", suffix: String = "Unknown") Person("Mr", "John", "M", "Doe", "Sr") Person(salutation = "Mr", firstName = "John", lastName = "Doe") Person(firstName = "John", middleName = "M", lastName = "Doe") Person(firstName = "John") Person(lastName = "Doe") Person(firstName = "John", lastName = "Doe")
  • 31.
  • 32.
    PATTERN MATCHING def parseArgument(arg:String, value: String) = (arg, value) match { }
  • 33.
    PATTERN MATCHING def parseArgument(arg:String, value: String) = (arg, value) match { case ("-h" | "--help", nil) => displayHelp() }
  • 34.
    PATTERN MATCHING def parseArgument(arg:String, value: String) = (arg, value) match { case ("-h" | "--help", nil) => displayHelp() case ("-l" | "--log-level", level) => setLogLevel(level) }
  • 35.
    PATTERN MATCHING def parseArgument(arg:String, value: String) = (arg, value) match { case ("-h" | "--help", nil) => displayHelp() case ("-l" | "--log-level", level) => setLogLevel(level) case (bad, _) => badArgument(bad) }
  • 36.
    PATTERNS // Constant patterns case0 => "zero” case true => "true" case "hello" => "you said hello” // Data structure patterns case List(0, _, _) => "a three-element list with 0 as the first element” case List(1, _*) => "a list beginning with 1, having any number of elements” // Constructor patterns case Person(_,_,_,"Smith",_) => "found a Smith” case Person(_,first,middle,"Smith",_) => s"found $first $middle Smith”
  • 37.
  • 39.
    GETTING STARTED • FunctionalProgramming Principles in Scala – coursera.com • Introduction to Scala – bigdatauniversity.com • Scala Cookbook by Alvin Alexander • Programming Scala by Dean Wampler & Alex Payne
  • 40.

Editor's Notes

  • #2 Takeaways What is Scala? Why choose Scala? Why Scala in a Java 8 world?
  • #3 Scala is multi paradigm language that was released in 2004 Scala is an Acronym for “Scalable Language” Martin Ordersky is the inventor of Scala. He is one of the designers of Java Generics and the author of the current java compiler What is Scala? Scala is Functional
  • #4 Functional languages are scalable because they make writing code without side effects easier Scala is a full blown functional language like Erlang, Haskell, and Clojure Scala is also Object Oriented https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/BalticServers_data_center.jpg/1280px-BalticServers_data_center.jpg
  • #6 Like any object oriented language Scala has objects, classes, and inheritance
  • #7 Scala runs in the JVM Scala code compiles to .class files Write java code in Scala Scala can make use of Java’s ecosystem Adapted from https://www.flickr.com/photos/silveiraneto
  • #9 Scala is Scalable Scala is scalable because it is a functional language http://www.freeimages.com/photo/russian-nesting-dolls-1-1427892
  • #10 Companies like Twitter which must handle 200 million users a day and process 500 million tweets per day use Scala because it is scalable Other companies like Linkedin, Walmart, Amazon, and Apple choose Scala because it is scalable Projects like Apache Spark, Apache Kafka, Akka, and the Play Framework choose Scala because it is scalable Why is scalability important?
  • #11 Changing Hardware Before 2008 processors where increasing at a fast rate. To make a program faster we could scale up, throw bigger hardware at it. Now clock speeds are not increasing, the number of cores are increasing. To make a program faster we must scale out. The cloud also requires applications to scale out instead of up. We need scalable applications, but there is one problem. http://www.cnet.com/news/intel-says-to-prepare-for-thousands-of-cores/
  • #12 Scalability is hard Anyone who has dealt with threads know that scalability is not trivial issue What makes scalability so hard? http://www.freeimages.com/photo/1327383
  • #13 Code with side effects Side effects are things like 1 Modifying a variable 2. Modifying a data structure in place 3. Setting a field on an object 4 Reading or writing from a database Lets look mutability as a side effect
  • #14 As soon as you introduce a setter you have mutability But the real problem is when we have concurrent threads accessing shared mutable state This is called non-determinist code. Here is a code snippet that shows this problem of concurrent threads accessing shared mutable state There are three different possibilities when we run this code. 0,1, or 2 So what can we use to help minimize side effects?
  • #15 A functional language like Scala helps because it makes it easier to write side effect free code and give us the tools to avoid and minimize shared mutable state Lets look at some features of functional programming that help in writing side effect free code https://upload.wikimedia.org/wikipedia/commons/thumb/5/5d/BalticServers_data_center.jpg/1280px-BalticServers_data_center.jpg
  • #16 Functional programming gives us pure functions A function is pure if it is side effect free. Function is pure if it does nothing more than use it’s inputs and return a result Let look at an example of a pure function
  • #17 A function is considered pure if you can replace a function call with it’s result and your application does not change The benefit of pure function is that they can always be scaled. Another benefit of pure function is they are easy to test and less error prone
  • #18 Functional Programming also gives us First-class functions This Means functions can Assign to a variable Store inside a data structure Passed as an argument Returned https://www.flickr.com/photos/natalieguinsler/2280305531/in/photolist-4tvaoB-5vy82S-3scrH-c5XCP-nZMyAZ-eDE6rN-v5F8d-9jhEp9-4jFB3S-dCi1kK-iWsj7f-8epKGB-4K6foq-bxCQeh-2z1akv-4m9wqd-2z5M2y-EaKmp5-4m9yXQ-eu7sak-4m9AGN-4m5sTv-4m5y1H-2z1aje-7oVwvZ-9b3cJT-2igLHF-aCSppo-nt5kvf-fNSewG-nt5toQ-bpFnQU-epqeoS-pMXuba-aahXqx-2VaVJx-enXDxY-nFMsCC-7vX85E-4m9xJN-2VATt5-2z1goH-2z1at4-2z5LSm-eXJSfJ-2z1aqc-2VAG1Q-2VANkq-2z1arx-2Vwk3c
  • #20 Functional programming give us high order functions. A high order function can return functions or receive other functions as parameters
  • #21 So we just talked about why choose Scala? Scala is scalable because is functional. But It is also object oriented, runs in the jvm and can use Java’s great ecosystem
  • #22 But don’t we get a functional, Object oriented language that can use Java’s ecosystem with Java 8? So why do we need Scala in a Java 8 world? http://www.freeimages.com/photo/263237
  • #23 Java 8 has functional programming but Java 8 is not a full functional language therefore the functional programming in Java is limited. Java doesn’t have functional features such as tail recursion and lazy evaluation which are important for performance in functional languages Therefore it takes work to make Java scalable Scala on the other hand is scalable because it is a full functional language To show this point let’s look at how each language handles immutability http://www.freeimages.com/photo/russian-nesting-dolls-1-1427892
  • #24 Immutability is important to ensure side effect free code. Java and Scala handle immutability like night and day. Java’s approach is start with mutability and use immutability when needed Scala’s approach is to start with immutability and use mutability when needed To make a class immutable in Java, you must: All fields of the class must be final; 2. Can’t us default or no-argument constructors because all required fields must be initialized by the constructor 3. No setters Scala gives us immutable classes with the case class. With this single line of code we get everything from the Java example plus an implementation of the equals, hashCode, and toString methods
  • #25 Not only do we need immutable classes but we need immutable data structures as well Java approach is to provide immutable views of mutable data structures using utility class Scala gives us immutable data structures by default and gives us functions to operate on these data structures in an immutable way Scala makes immutability easy whereas with Java you have to work to make classes and data structures immutable Scala solves the problem of scalability, but there is more to choosing a language then just its capabilities. A language needs to allow a developer to write code as quickly as possible . Is Scala easy to use?
  • #26 Yes! Why choose Scala? Because Scala is expressive The expressiveness of Scala allows developers to write code quickly as possible by eliminating the need for boiler plate code In Fred Brook’s book The Mythical Man Month, Brooks argues that the average number of lines of code a programmer writes per day is constant no mater what language is used So if a program takes 10,000 lines in one language and 20,000 lines in another, Brooks asserts that it would take twice as long to write a program in the second language as it would in the first Lets look at some of the expressive features in Scala
  • #27 Have there been times when coding in Java that you wished that it had multiple inheritance? Like creating a BenchBarrow class. But don’t we get multiple inheritance in Java8 with default methods in interfaces. Yes Java 8 has multiple inheritance of behavior, but not state and default methods must be public Scala gives us multiple inheritance of both state and behavior with Traits Lets look at how traits make the BenchBarrow possible https://plus.google.com/photos/+JeanBezivin/albums/5741545258387077889/5741545266408420306?pid=5741545266408420306&oid=105933370793992913359
  • #28 BenchBarrow is possible because of multiple inheritance using Traits
  • #29 I’m sure you have seen this case numerous time where a constructor takes a large number of parameters that are not all required to be initialized. If we want this class to be immutable the recommend way to solve this problem is through the use of the builder pattern Lets take a look at the Builder Pattern for this Person class
  • #30 The builder pattern works and solves our problem but requires an awful lot of boiler plate code to construct an immutable instance of our person class Lets look at Scala approach to this problem
  • #31 From a previous slide we saw that we can create immutable classes using case classes Named parameters allows us easily reference the fields that we want to include when constructing a Person We get 32 different constructors using named parameters with our Person case class Expressive features liked Named parameters eliminates the need for patterns in Scala like the builder pattern
  • #32 In code we often need validate user input or validate that an object is constructed properly. And often we need to perform specific business logic based on how a Object is constructed Scala has Pattern matching which is like a switch statement on steroids Pattern matching make it easy to deal with different flavors of objects and provide specific business logic for each case Lets look at how pattern matching can help us parse command line arguments
  • #35 Not limited to matching one type
  • #36 Not limited to matching one type
  • #37 Patterns make it easy to validate and provide specific business logic form matching cases
  • #38 Scala is expressive and has features that allow developer to write code as quickly as possible like 1. Multiple inheritance 2. Named parameters 3. Pattern matching But there are also other features such as: 1. Multiline strings 2. Type inference 3. Options 4. Tuples 5. For comprehension
  • #39 Why Scala in a Java 8 world? Scala is scalable. It is the right tool for the problem we need to solve But there is more to a language then just its capabilities Scala is also expressive. The expressiveness of Scala allows a developer to write code as quickly as possible and eliminate the need for boiler plate code
  • #40 Here’s how to get started