Solidity – What is the Immutable Keyword?

immutablekeywordsoliditysolidity-0.6.xstate-variable

What is the immutable keyword in Solidity and how do I use it?

Best Answer

The immutable keyword was added to Solidity in 0.6.5.

State variables can be marked immutable which causes them to be read-only, but assignable in the constructor. The value will be stored directly in the code.

From the docs:

Variables declared as immutable are a bit less restricted than those declared as constant: Immutable variables can be assigned an arbitrary value in the constructor of the contract or at the point of their declaration. They cannot be read during construction time and can only be assigned once.

An example code snippet is as follows:

pragma solidity ^0.6.5;

contract TestImmutable {
    uint256 public immutable a;

    // This is a valid constructor
    constructor (uint256 _a) public {
        a = _a;
    }

    // This is invalid and will not compile
    function setA (uint256 _a) public {
        a = _a;
    }
}

It is important to note that the contract creation code generated by the compiler will modify the contract’s runtime code before it is returned by replacing all references to immutables by the values assigned to the them. This is important if you are comparing the runtime code generated by the compiler with the one actually stored in the blockchain.