What are functions in Solidity?

Overview

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.

Function declaration

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.

Syntax

function functionName(parameters) scope returns() {
    // body
}

Parameters

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.

Scope

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.

Return values

It specifies a list of values that are returned by the function. It is required only when we return some values from the function.

Pure and view functions

Solidity also specifies a type that defines the accessibility behavior of the function. It can be defined between function scope and return values:

Function invocation/calling

To execute a function, we need to call or invoke it. We need to pass the required parameters along with the function name.

Example

The example below shows how to declare a function in Solidity.

pragma solidity ^0.5.0;
contract HelloWorld {
// declare state variable
string message = "Hello World";
// create a function to return message
function getMessage() public view returns(string memory) {
return message;
}
}

Explanation

  • Line 3: We create a contract HelloWorld.
  • Line 5: We declare a state variable message.
  • Line 8: We create a function getMessage() that returns the value of the message.

Free Resources