In programming, immutable refers to an object, data structure, or variable that cannot be modified after it's created. The term immutable is used both as a concept and as a keyword in various programming languages.
Many programming languages and smart contract languages use the immutable keyword to declare variables or properties that cannot be changed after initialization. Programming languages that do not have the explicit immutable keyword, achieve the same effect using different keywords or specific designs or declarations. Here's how immutable is used in different contexts:
immutable keyword and achieves immutability through final variables and careful class design.readonly for runtime constants, const for compile-time constants, and init for init-only properties. So it has immutable objects in concept, but not by name.
immutable keyword for contract-level variables that can only be assigned once during contract creation.immutable keyword through careful variable declaration and initialization.
Let's look at a practical Solidity example:
contract ExampleContract {
address public immutable owner;
uint256 public constant MINIMUM_STAKE = 100 ether;
constructor() {
owner = msg.sender;
}
}
In this example:
owner variable is declared as immutable. It can only be set once in the constructor and cannot be changed afterward.MINIMUM_STAKE is declared as a constant, which is implicitly immutable. Its value is fixed at compile-time and cannot be changed.
Using immutable variables in programming and smart contracts provides several advantages:
Immutability as a concept extends beyond programming languages. Here are some real-world examples: