I came across below example from the Solidity Documentation
and have similar code in my project and want to set default value
to key parameter if the key is not passed from the caller
pragma solidity ^0.4.0;
contract C {
function f(uint key, uint value) public {
// ...
}
function g() public {
// named arguments
f({value: 2, key: 3});
}
}
My questions are -
default parameters
?Appreciate the help?
Solidity does not support default parameters, but it is on their roadmap (see https://github.com/ethereum/solidity/issues/232). To work around this, just use function overloading:
pragma solidity ^0.4.0;
contract C {
function f(uint key, uint value) public {
// ...
}
function h(uint value) public {
f(123, value);
}
function g() public {
// named arguments
f({value: 2, key: 3});
}
function i() public {
h({value: 2});
}
}
Openzeppelin does a great job exemplifying how you can make "default" arguments. Check out their SafeMath Library.
In it, they have two sub (subtraction) contracts that are identical visibility and mutability wise- but a key difference:
function sub(
uint256 a,
uint256 b
)internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
The first one by default takes two arguments a & b (which will be subtracted). If a third argument is not given (the error statement) it will default to
SafeMath: subtraction overflow
If a third argument is given, it will replace that error statement.
Essentially:
pragma solidity >=0.6.0 <0.9.0;
contract C {
function f(unit value) public {
uint defaultVal = 5;
f(defaultVal, value);
function f(uint key, uint value) public {
// ...
}
function g() public {
// named arguments
f(2, 3);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With