0
0
Blockchain / Solidityprogramming~5 mins

Function overloading in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

Function overloading lets you use the same function name for different tasks by changing the inputs. This makes your code easier to read and organize.

You want to create multiple ways to send tokens depending on input types.
You need different versions of a function to handle various data formats.
You want to keep function names simple but handle different numbers of inputs.
You want to improve code clarity by grouping similar actions under one name.
Syntax
Blockchain / Solidity
function functionName(type1 param1) public returns (type) { ... }
function functionName(type1 param1, type2 param2) public returns (type) { ... }
Each function must have a unique list of input types or number of inputs.
The return type alone cannot distinguish overloaded functions.
Examples
Two transfer functions: one sends tokens, the other sends tokens with a note.
Blockchain / Solidity
function transfer(address to, uint amount) public { ... }
function transfer(address to, uint amount, string memory note) public { ... }
Calculate function works with one or two numbers.
Blockchain / Solidity
function calculate(uint a, uint b) public returns (uint) { ... }
function calculate(uint a) public returns (uint) { ... }
Sample Program

This contract shows three 'add' functions with different inputs. You can add one, two, or three numbers using the same function name.

Blockchain / Solidity
pragma solidity ^0.8.0;

contract OverloadExample {
    uint public lastResult;

    // Add two numbers
    function add(uint a, uint b) public {
        lastResult = a + b;
    }

    // Add three numbers
    function add(uint a, uint b, uint c) public {
        lastResult = a + b + c;
    }

    // Add one number to itself
    function add(uint a) public {
        lastResult = a + a;
    }
}
OutputSuccess
Important Notes

Function overloading helps keep your contract clean and easy to understand.

Make sure each overloaded function has different input types or counts.

Overloading is common in Solidity, the main blockchain programming language.

Summary

Function overloading lets you use one name for similar actions with different inputs.

It makes your code simpler and easier to read.

Each overloaded function must differ by input types or number of inputs.