A function is a block of code or a collection of statements compartmentalized together to perform a specific task. It takes an input, does some processing, and produces an output.
In Solidity, we can declare a function using the function
keyword, followed by the function name, a set of function parameters wrapped inside ()
, function scope, return values, and the function body.
function functionName(parameters) scope returns() {
// body
}
It specifies a list of parameters that are accepted by the function. It contains the type and the name of each parameter separated by a comma. It can be empty as well.
In Solidity, the scope can be any of the following:
private
: The function can be accessed only from inside the contract.internal
: The function can be accessed from inside the contract as well as the child contracts that inherit it.external
: The function can be accessed only from outside the contract. Other functions of the contract cannot invoke it.public
: The function can be accessed from everywhere.It specifies a list of values that are returned by the function. It is required only when we return some values from the function.
Solidity also specifies a type that defines the accessibility behavior of the function. It can be defined between function scope and return values:
pure
function doesn’t read or modify the variables of the state. The detailed information about pure functions can be found here: What are pure functions in Solidity?view
function only reads but doesn’t modify the variables of the state. The detailed information about view functions can be found here: What is a view function in Solidity?To execute a function, we need to call or invoke it. We need to pass the required parameters along with the function name.
The example below shows how to declare a function in Solidity.
pragma solidity ^0.5.0;contract HelloWorld {// declare state variablestring message = "Hello World";// create a function to return messagefunction getMessage() public view returns(string memory) {return message;}}
HelloWorld
.message
.getMessage()
that returns the value of the message
.