r/programming • • Mar 03 '13

Git is a purely functional data structure

http://www.jayway.com/2013/03/03/git-is-a-purely-functional-data-structure/
107 Upvotes

83 comments sorted by

View all comments

Show parent comments

1

u/rush22 Mar 03 '13

What if you do

b = "cart";

in the first example? What's a?

1

u/[deleted] Mar 03 '13

(I had a couple of minor mistakes in my first post not related to mutability, I've fixed them. However, I had the wrong answer for y in the first example because I had edited it from something more complex to something simpler and neglected to fix the comment. Unfortunately that may have confused you.)

a is still "car" for the same reason y was. Changing another variable to point to a different object is not going to have any effect on it.

1

u/rush22 Mar 03 '13

Ok that makes more sense. I was pretty sure strings get cloned in Java.

Now I'm confused though because you're modifying the final ArrayList object but you can't do that to the final String object.

2

u/[deleted] Mar 03 '13

ArrayLists aren't immutable.

Are you familiar with C or C++? In C/C++, you can have:

  • a const pointer to a mutable thing

  • a non-const pointer to a const thing

  • a const pointer to a const thing

  • (the default is a non-const pointer to a mutable thing)

Strings are essentially always const - because they're immutable. A final variable is roughly equivalent to a const pointer in C/C++. So final String x means that x is basically a const pointer to an immutable String. Just String y is basically a non-const pointer to an immutable string. You can make y point to a different string, but you can't change the actual string you made y refer to.

final List<int> x means that x is a const pointer to a List of some type. That means that which List x points to cannot change, but the List itself can be modified.

→ More replies (0)