Scala:	
  immutability	
  
Why	
  immutability?	
  
•  Keep	
  control	
  of	
  your	
  state	
  
– Avoid	
  unexpected	
  values	
  
•  Avoid	
  concurrent	
  state	
  issues	
  
•  Most	
  container	
  types	
  are	
  immutable	
  by	
  
default	
  (collec>ons,	
  for	
  example)	
  
Use	
  vals	
  
// Create immutable variable with a value
val temperature = BigInt(-10)

// Does not compile, cannot reassign to val
now = BigInt(5)
Don't	
  modify,	
  create	
  
// Create immutable variable with a value
val temperature = BigInt(-10)

// Get the absolute value as a new instance
val absolute = temperature.abs
Use	
  copy	
  
// Case classes give you a copy method for free
case class User(name: String, email: String)

// Use to create new copies of the same class
val bilbo = User("Bilbo", "bilbo@shi.re")
val newBilbo = bilbo.copy(email = "bilbo@valin.or")
Hide	
  your	
  vars	
  
class User(name: String) {


// Public by default, hide them!

private var status = Satus.Initial


def transition(s: Status) {

 
status = s

}
}
Be	
  mindful	
  of	
  
•  Modifying	
  immutable	
  nested	
  structures	
  
•  Fields	
  that	
  get	
  ini>alized	
  with	
  each	
  new	
  
instance	
  
•  Mutable	
  state	
  that	
  is	
  not	
  labeled	
  as	
  private	
  
•  Closing	
  over	
  mutable	
  state	
  
www.boldradius.com	
  

Immutability in Scala

  • 1.
  • 2.
    Why  immutability?   • Keep  control  of  your  state   – Avoid  unexpected  values   •  Avoid  concurrent  state  issues   •  Most  container  types  are  immutable  by   default  (collec>ons,  for  example)  
  • 3.
    Use  vals   //Create immutable variable with a value val temperature = BigInt(-10) // Does not compile, cannot reassign to val now = BigInt(5)
  • 4.
    Don't  modify,  create   // Create immutable variable with a value val temperature = BigInt(-10) // Get the absolute value as a new instance val absolute = temperature.abs
  • 5.
    Use  copy   //Case classes give you a copy method for free case class User(name: String, email: String) // Use to create new copies of the same class val bilbo = User("Bilbo", "bilbo@shi.re") val newBilbo = bilbo.copy(email = "bilbo@valin.or")
  • 6.
    Hide  your  vars   class User(name: String) { // Public by default, hide them! private var status = Satus.Initial def transition(s: Status) { status = s } }
  • 7.
    Be  mindful  of   •  Modifying  immutable  nested  structures   •  Fields  that  get  ini>alized  with  each  new   instance   •  Mutable  state  that  is  not  labeled  as  private   •  Closing  over  mutable  state  
  • 8.