O'Reilly logo

Scala Functional Programming Patterns by Atul S. Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Persistent data structures

As you can guess by now, immutability is the underlying big theme. The following Java code reverses a list in place:

List<Integer> list = Lists.newArrayList(1,2,3,4); 
// List<Integer> refList = Lists.newArrayList(list); // 1 
List<Integer> refList = list; 
Collections.reverse(list); 

System.out.println(list); 
System.out.println(refList);

The problem is when we do the reversal in place, the code using the list as a reference also sees the change. To prevent this, we need to use the statement at the part labeled as 1—the defensive copy technique. The other problem with changing the list in place is thread safety. We need to carefully synchronize the list access so we stay away from heisenbugs. To know more about them, refer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required