The need for functional programming languages is more important than ever with the current hardware and software trends. Scala has become the number one choice for functional programming languages and is becoming the language of choice for many development teams. But with the introduction of functional programming in Java 8 is Scala still relevant and needed?
23. 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)
27. 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
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
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”
39. 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
Takeaways
What is Scala?
Why choose Scala?
Why Scala in a Java 8 world?
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
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
Like any object oriented language Scala has objects, classes, and inheritance
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
Scala is Scalable
Scala is scalable because it is a functional language
http://www.freeimages.com/photo/russian-nesting-dolls-1-1427892
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?
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/
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
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
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?
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
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
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
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
Functional programming give us high order functions.
A high order function can return functions or receive other functions as parameters
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
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
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
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
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?
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
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
BenchBarrow is possible because of multiple inheritance using Traits
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
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
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
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
Not limited to matching one type
Not limited to matching one type
Patterns make it easy to validate and provide specific business logic form matching cases
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
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