Optics
Optics are abstractions to update immutable data structures elegantly. One form of optics is Lens
(or lenses, depending on the library implementation). A Lens
is a functional reference that can focus (hence the name) into a structure and read, write, or modify its target:
typealias GB = Int data class Memory(val size: GB) data class MotherBoard(val brand: String, val memory: Memory) data class Laptop(val price: Double, val motherBoard: MotherBoard) fun main(args: Array<String>) { val laptopX8 = Laptop(500.0, MotherBoard("X", Memory(8))) val laptopX16 = laptopX8.copy( price = 780.0, motherBoard = laptopX8.motherBoard.copy( memory = laptopX8.motherBoard.memory.copy( size = laptopX8.motherBoard.memory.size * 2 ) ) ) println("laptopX16 = $laptopX16") }
To create a new Laptop
value from an existing one, we need to use several nested copy methods and references. In this example, it isn't as...