Immutable vs Mutable types

前端 未结 16 1655
感情败类
感情败类 2020-11-21 05:51

I\'m confused on what an immutable type is. I know the float object is considered to be immutable, with this type of example from my book:

class         


        
16条回答
  •  抹茶落季
    2020-11-21 06:44

    It would seem to me that you are fighting with the question what mutable/immutable actually means. So here is a simple explenation:

    First we need a foundation to base the explenation on.

    So think of anything that you program as a virtual object, something that is saved in a computers memory as a sequence of binary numbers. (Don't try to imagine this too hard, though.^^) Now in most computer languages you will not work with these binary numbers directly, but rather more you use an interpretation of binary numbers.

    E.g. you do not think about numbers like 0x110, 0xaf0278297319 or similar, but instead you think about numbers like 6 or Strings like "Hello, world". Never the less theses numbers or Strings are an interpretation of a binary number in the computers memory. The same is true for any value of a variable.

    In short: We do not program with actual values but with interpretations of actual binary values.

    Now we do have interpretations that must not be changed for the sake of logic and other "neat stuff" while there are interpretations that may well be changed. For example think of the simulation of a city, in other words a program where there are many virtual objects and some of these are houses. Now may these virtual objects (the houses) be changed and can they still be considered to be the same houses? Well of course they can. Thus they are mutable: They can be changed without becoming a "completely" different object.

    Now think of integers: These also are virtual objects (sequences of binary numbers in a computers memory). So if we change one of them, like incrementing the value six by one, is it still a six? Well of course not. Thus any integer is immutable.

    So: If any change in a virtual object means that it actually becomes another virtual object, then it is called immutable.

    Final remarks:

    (1) Never mix up your real-world experience of mutable and immutable with programming in a certain language:

    Every programming language has a definition of its own on which objects may be muted and which ones may not.

    So while you may now understand the difference in meaning, you still have to learn the actual implementation for each programming language. ... Indeed there might be a purpose of a language where a 6 may be muted to become a 7. Then again this would be quite some crazy or interesting stuff, like simulations of parallel universes.^^

    (2) This explenation is certainly not scientific, it is meant to help you to grasp the difference between mutable and immutable.

提交回复
热议问题