Mutable vs immutable objects

前端 未结 12 1720
囚心锁ツ
囚心锁ツ 2020-11-22 09:17

I\'m trying to get my head around mutable vs immutable objects. Using mutable objects gets a lot of bad press (e.g. returning an array of strings from a method) but I\'m hav

12条回答
  •  温柔的废话
    2020-11-22 09:34

    Shortly:

    Mutable instances is passed by reference.

    Immutable instances is passed by value.

    Abstract example. Lets suppose that there exists a file named txtfile on my HDD. Now, when you are asking me to give you the txtfile file, I can do it in the following two modes:

    1. I can create a shortcut to the txtfile and pass shortcut to you, or
    2. I can do a full copy of the txtfile file and pass copied file to you.

    In the first mode, the returned file represents a mutable file, because any change into the shortcut file will be reflected into the original one as well, and vice versa.

    In the second mode, the returned file represents an immutable file, because any change into the copied file will not be reflected into the original one, and vice versa.

提交回复
热议问题