What is immutability and why should I worry about it?

前端 未结 15 1087
无人共我
无人共我 2020-12-07 09:51

I\'ve read a couple of articles on immutability but still don\'t follow the concept very well.

I made a thread on here recently which mentioned immutability, but as

15条回答
  •  渐次进展
    2020-12-07 10:29

    Things that are immutable never change. Mutable things can change. Mutable things mutate. Immutable things appear to change but actually create a new mutable thing.

    For example here is a map in Clojure

    (def imap {1 "1" 2 "2"})
    (conj imap [3 "3"])
    (println imap)
    

    The first line creates a new immutable Clojure map. The second line conjoins 3 and "3" to the map. This may appear as if it is modifying the old map but in reality it is returning a new map with 3 "3" added. This is a prime example of immutability. If this had been a mutable map it would have simply added 3 "3" directly to the same old map. The third line prints the map

    {3 "3", 1 "1", 2 "2"}
    

    Immutability helps keep code clean and safe. This and other reasons is why functional programming languages tend to lean towards immutability and less statefulness.

提交回复
热议问题