I have a contract that handles insurances and I would like to be able to get a single instance either by index or by address. To this end I wrote two functions:

function getInsurance(uint index) constant returns (string, InsuranceStatus) {
    Insurance insurance = insurances[insuranceList[index]];
    return (insurance.name, insurance.status);

function getInsurance(address insuranceAddress) constant returns (string, InsuranceStatus) {
    Insurance insurance = insurances[insuranceAddress];
    return (insurance.name, insurance.status);

when I test this, the second function (the one with the address parameter) does not return any data.

The compiler does not complain but I'm wondering if this is this supposed to work.


It's supposed to work because the "parameters differ in number or type". https://github.com/ethereum/wiki/wiki/Solidity-Features

Possibly a matter of taste, but I would consider a distinguished function to return just the address from the index and avoid repetition:

function getInsuranceAtIndex(uint index) constant returns(address insuranceAddress) {
   return insuranceList[index];

The "returns" are little unfamiliar. Is it possible to post a snippet that compiles and runs so we can poke at it?

  • thank you for your answer, I ended up naming the functions differently to make the interface clearer and hence have o working example anymore. – Micha Roon Dec 30 '16 at 6:18

What I find useful is a bidirectional lookup table which relies on casting and hashing the entry and the index as the keys to the other. Providing either to the get function returns the other. Hashing the key stops any possible key collisions.

uint public id = 1; 

// easier to cast address and bytes32 to uint
mapping (bytes32 => uint) lut;

function add(uint _element)
    returns (uint)
    lut[sha3(_element)] = id;
    lut[sha3(id)] = _element;

function get(uint idOrElement)
    returns (uint)
    return lut[sha3(idOrElement)];

In my own implementations I actually have these functions as internal and use public wrapper functions to do the necessary parameter casting.


The method id is bytes4(sha3("getInsurance(uint)") for the first function, and for the second is bytes4(sha3("getInsurance(address)") as you remark the signature depends on the parameters types, so you get different IDs.

For the return issue, I think you should provide the contract code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.