What is a view function in Solidity?
In Solidity, a function that only reads but doesn’t alter the state variables defined in the contract is called a View Function.
If the statements below are found in a view function, the compiler will consider them as altering state variables and return a warning.
- Modify/over-write state variables.
- Create new contracts.
- Invoke a function that is not pure or view.
- Emit event.
- Using certain opcodes in inline assembly.
- Use
selfdestruct. - Use low-level function calls.
- Send Ether along with function calls.
Note: All the getter functions are view functions by default.
Syntax
function <function-name>() <access-modifier> view returns() {
// function body
}
Code
In the code snippet below, we will see how to create a view function in Solidity.
pragma solidity ^0.5.0;contract Example {// declare a state variableuint number1 = 10;// creating a view function// it returns sum of two numbers that are passed as parameter// and the state variable number1function getSum(uint number2, uint number3) public view returns(uint) {uint sum = number1 + number2 + number3;return sum;}}
Explanation
-
Line 3: In the above code, we create a contract named
Example. -
Line 5: We declare a static variable
number1. -
Line 10: We define a view function named
getSum(). -
Line 11-12: This function accepts two parameters
number2andnumber3, calculates the sum ofnumber1,number2, andnumber3, and returns thesum.
Since getSum() is a view function, we can read variable number1 but can’t modify it.