is good
[Def] Immutable - an object which state cannot be changed after it has been created.
Objects should be immutable - Java article from 2014
is good
Objects should be immutable - Java article from 2014
is good
Objects should be immutable - Java article from 2014
Concurrent programming problem with multiple threads sharing a mutable resource
When one logical part depends on the side effect from another logical part in the program
Unwanted behaviour from sharing an object's state in different parts of the program
Occurring when we change an object that is used as a key in a data structure such as Map<Date, Int>
public class Stack {
private int size;
private String[] items;
public void push(String item) {
size++;
if (size > items.length) {
throw new RuntimeException("stack overflow");
}
items[size] = item;
}
}
In the context of pure functional languages, PatternMatching is a dispatch mechanism: choosing which variant of a function is the correct one to call. Inspired by standard mathematical notations.
factorial(0) ::= 1
factorial(n) ::= n * factorial(n-1)
TLDR: Pattern matching lets us do this:
Traditional approach
def toYesOrNo(choice: Int): String = choice match {
case 1 => "yes"
case 0 => "no"
case _ => "error"
}
Traditional approach
def toYesOrNo(choice: Int): String = choice match {
case 1 | 2 | 3 => "yes"
case 0 => "no"
case _ => "error"
}
Traditional approach
def parseArgument(arg: String) = arg match {
case "-h" | "--help" => displayHelp
case "-v" | "--version" => displayVerion
case whatever => unknownArgument(whatever)
}
Typed pattern
def parseArgument(arg: String) = arg match {
case "-h" | "--help" => displayHelp
case "-v" | "--version" => displayVerion
case whatever => unknownArgument(whatever)
}
f(1) // “integer: 1”
f(1.0) // “a double”
f(“hello”) // “I want to say hello”
Collection pattern matching
def length[A](list : List[A]) : Int = list match {
case _ :: tail => 1 + length(tail)
case Nil => 0
}
Collection pattern matching
def member[T](x:T, list:List[T]): Boolean = list match {
case Nil => false
case `x` :: _ => true
case _ :: tail => member(x, tail)
}
member(1, List(1,2,3))
member(2, List(1,2,3))
member(3, List(1,2,3))
member(4, List(1,2,3))
member("Kamen", List("Hopper", "Kamen", "Panda"))
member("Dobri", List("Hopper", "Kamen", "Panda"))
Advanced pattern matching
Problems
A data structure that has flatMap and unit defined
AND
What is a monad?
What is this?
Why is this needed?