Skip to content

Instantly share code, notes, and snippets.

@ttldtor
Created December 18, 2014 19:37
Show Gist options
  • Save ttldtor/047f7c6b20e44edeff94 to your computer and use it in GitHub Desktop.
Save ttldtor/047f7c6b20e44edeff94 to your computer and use it in GitHub Desktop.
import shapeless._
// A pair of ordinary case classes ...
case class Address(street : String, city : String, postcode : String)
case class Person(name : String, age : Int, address : Address)
// Some lenses over Person/Address ...
val nameLens = lens[Person] >> 'name
val ageLens = lens[Person] >> 'age
val addressLens = lens[Person] >> 'address
val streetLens = lens[Person] >> 'address >> 'street
val cityLens = lens[Person] >> 'address >> 'city
val postcodeLens = lens[Person] >> 'address >> 'postcode
scala> val person = Person("Joe Grey", 37, Address("Southover Street", "Brighton", "BN2 9UA"))
person: Person = Person(Joe Grey,37,Address(Southover Street,Brighton,BN2 9UA))
scala> val age1 = ageLens.get(person) // Read field, note inferred type
age1: Int = 37
scala> val person2 = ageLens.set(person)(38) // Update field
person2: Person = Person(Joe Grey,38,Address(Southover Street,Brighton,BN2 9UA))
scala> val person3 = ageLens.modify(person2)(_ + 1) // Transform field
person3: Person = Person(Joe Grey,39,Address(Southover Street,Brighton,BN2 9UA))
scala> val street = streetLens.get(person3) // Read nested field
street: String = Southover Street
scala> val person4 = streetLens.set(person3)("Montpelier Road") // Update nested field
person4: Person = Person(Joe Grey,39,Address(Montpelier Road,Brighton,BN2 9UA))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment