"Functional code is characterised by one thing: the absence of
side effects. It doesn’t rely on data outside the current
function, and it doesn’t change data that exists outside the
current function. Every other “functional” thing can be derived
from this property. Use it as a guide rope as you learn.”
- - Mary Rose Cook
- https://maryrosecook.com/blog/post/a-practical-introduction-to-functional-
programming
Slide 8
Slide 8 text
SO I CAN GO FUNCTIONAL
WITH JAVA?
Slide 9
Slide 9 text
Lisp | John McCarthy and Steve Russell | 1958
Slide 10
Slide 10 text
Immutability
Slide 11
Slide 11 text
Read-Modify-Write
Slide 12
Slide 12 text
class Car(var noOfDrivers: Int)
Slide 13
Slide 13 text
No content
Slide 14
Slide 14 text
class Car(val noOfDrivers: Int)
Slide 15
Slide 15 text
No content
Slide 16
Slide 16 text
Using functions right
Slide 17
Slide 17 text
No content
Slide 18
Slide 18 text
"A pure function is a function that, given the same input, will
always return the same output and does not have any
observable side effect."
- Professor Franklin Risby's
- Mostly Adequate Guide to Functional Programming
Slide 19
Slide 19 text
fun add(x: Int): Int {
val y: Int = readNumFromFile()
return x + y
}
Impure
Slide 20
Slide 20 text
fun add(x: Int, y: Int) = x + y
Pure
Slide 21
Slide 21 text
fun plus2(x: Int): Int {
val y = x + 2
cache(y)
return y
}
Impure
Slide 22
Slide 22 text
fun plus2(x: Int) = x + 2
Pure
Slide 23
Slide 23 text
"The name of a variable, function or class should answer the
big questions such as why it exists, what it does, how it is
used."
Aiden Mc Raft commenting Robert C. Martin’s Clean Code: A
Handbook of Agile Software Craftsmanship
Slide 24
Slide 24 text
Demystifying functions
Slide 25
Slide 25 text
fun add(x: Int, y: Int) = x + y
Slide 26
Slide 26 text
val add = fun add(x: Int, y: Int) = x + y
Slide 27
Slide 27 text
fun doSomething(function: (Int, Int) -> Int) {
…
}
Slide 28
Slide 28 text
data class User(val name: String,
val amount: Int,
val onClick: (User) -> Unit)
fun applyOperation(operation: Operation): (Int, Int) -> Int {
val add = fun (x: Int, y: Int) = x + y
val sub = fun (x: Int, y: Int) = x - y
when (operation) {
Operation.ADD -> return add
Operation.SUB -> return sub
}
}
Slide 32
Slide 32 text
applyOperation(Operation.ADD) (1, 3)
Slide 33
Slide 33 text
Functional Operators
Slide 34
Slide 34 text
public inline fun …Iterable.map(transform: (T) -> (R)): …List
val myList = listOf(2, 4, 6, 8, 10, 12)
val myNewList = myList.map { it * 2 }
// [ 4, 8, 12, 16, 20, 24 ]
Slide 35
Slide 35 text
none(…)
val myList = listOf(2, 4, 6, 8, 10, 12)
myList.none { it % 7 == 0 }
// true
Slide 36
Slide 36 text
filter(…)
val myList = listOf(4, 8, 12, 16, 20, 24)
myList.filter { it > 20 }
// [ 24 ]