language • Functional programming emphasizes programming with… • first-class functions and • immutable data structures • Concurrency safety • Fault tolerance in distributed systems 3
it can be replaced with its corresponding value without changing the program’s behavior (Mitchell 2002) • A function is referentially transparent if its application to the same value evaluates to the same result 5
types (Int, Boolean, Double, etc.) • val members, lazy val members • Simple case classes are immutable by default – No declared or inherited var members – All field types immutable • Value classes wrapping immutable types 8
case class Person(name: String, age: Int) trait Printable extends Any { def print(): Unit = println(this) } class Meter(val value: Double) extends AnyVal with Printable { def +(m: Meter): Meter = new Meter(value + m.value) } Universal trait
• Others consider reference immutability – Does a reference enable mutating an object? • Three different immutability properties: – Deep immutability – Shallow immutability – Conditional deep immutability 14 Fields not reassignable but may refer to mutable objects
for classes, traits, and objects? • Question 2: for classes/traits/objects that are not deeply immutable: what are the most common reasons why stronger immutability properties are not satisfied? 15
each template maintain value from immutability lattice: { bot, deep, shallow, mut } • Implementation based on Reactive Async which provides lattice-based variables with cyclic dependency resolution – See my talk at Scala Days Berlin 2016 16 https://github.com/luax/scala-immutability-plugin
projects is immutable – That is, satisfies one of the immutability properties • Deep immutability is often conditional: depends on instantiation of type parameters or abstract types • Low percentage of mutable case classes • Very low percentage of mutable singleton objects 23
80 % Parent type mutable Reassignable field (private) Parent type unknown Reassignable field (public) Parent type unknown Reassignable field (private) Parent type mutable Scala std library (v2.11.8) Looking only at mutable templates..
% 5 % 33 % 24 % 34 % Parent type shallow immutable val field with unknown type val field with mutable type val field with shallow immutable type Other val field with mutable type Parent type shallow immutable val field with unknown type
Immutability in Scala. PLACES@ETAPS 2017: 21-27 • Ludvig Axelsson. Immutability: An Empirical Study in Scala. Master’s thesis. KTH Royal Institute of Technology, Stockholm, Sweden. forthcoming 28
type definitions in popular open source projects is immutable – Statistics for case classes and non-case classes very different – Very low percentage of mutable singleton objects • Is it time for more support from the language? 29