Solidity

Solidity View Functions

Solidity View Functions Main Tips

  • In Solidity view functions are functions, that are promised not to modify the state.
  • Getter methods are a perfect example of view functions, as they are only used to retrieve a value instead of modifying the element, and are actually marked view.

Solidity View Functions

Functions are declarable as view, making them promise not to modify the state, thus only being used for viewing the state.

Here’s a list of conditions for a statement to be considered as “modifying the state”:

  1. State variables being written to.
  2. Events being emitted.
  3. Other contracts being created.
  4. selfdestruct being used.
  5. Ether being sent via calls.
  6. Calling functions that are not marked view or pure.
  7. Low-level calls being used.
  8. Inline assembly containing certain opcodes being used.

Example

pragma solidity ^0.4.16;

contract cont {
    function func(uint x, uint y) view returns (uint) {
        return x * (y + 42) + now;
    }
}

 

Try on Remix Try live on Hosting

Note: constant is actually an alias to the keyword view.

Warning: enforcing view method not to modify the state has not been implemented yet. 

Read previous post:
Solidity Constant State Variables

Solidity Constant State Variables Main Tips In Solidity state variables can be declared as constant, so they have to be...

Close