Open In App

Solidity Function Overloading

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Function overloading in Solidity lets you specify numerous functions with the same name but varying argument types and numbers.
Solidity searches for a function with the same name and parameter types when you call a function with certain parameters. Calls the matching function. Compilation errors occur if no matching function is found.

Function overloading lets you construct a collection of functions that accomplish similar operations but utilize various data types. It simplifies coding. Function overloading may complicate your code, particularly if you write several overloaded functions with multiple arguments.

Below is the Solidity program to implement Function Overloading:

Solidity




// Solidity program to implement 
// Function Overloading
pragma solidity ^0.8.0;
  
contract OverloadingExample {
    
  // Function with the same name but 
  // different parameter types
  function add(uint256 a, uint256 b) public pure returns (uint256) 
  {
    return a + b;
  }
      
  function add(string memory a, string memory b) public pure returns (string memory) 
  {
    return string(abi.encodePacked(a, b));
  }
}


Explanation: 

  • The OverloadingExample contract defines two add functions with different parameter types. 
  • The first function adds two uint256 values and returns an uint256. 
  • The second function concatenates two strings and returns them.

Output:

Function Overloading Output

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads