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.
Variables declared as immutable
immutable
are a bit less restricted than those declared as constantconstant
: 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.