# What is the most efficient way to emulate sum types on Solidity?

``````struct Weapon {
int atk;
int duration;
}
struct Armor {
int def;
int duration;
}
``````

then, how do you write this:

``````struct Equipment {
/* can be either an Weapon or an Armor */
}
function atkOrDef(Equipment equip) returns(int) {
/* returns the atk if an Weapon, or the def if an Armor */
}
``````

If that isn't possible, how would you do that?

Solidity does have inheritance. You could define a class Equipment that is extended by classes Weapon and Armor (you have to define them separately. Then add an attribute that uniquely distinguishes from Weapon and Equipment (an integer with a predefined value). Then you could use this attribute in the atkOrDef (call a getter method of the attribute) and use it to determine if Equipment equip is either Weapon or Armor.

Something along the lines of:

``````contract Equipment {
uint atk;
uint duration;
// Define an attribute that uniquely distinguishes Weapon from
// Armor
uint unique;

function Equipment(uint atk_param, uint duration_param) {
atk = atk_param;
duration = duration_param;
}

// getter method for the attribute
function getWeaponOrArmor() constant public (uint) {
return unique;
}
}

contract Weapon is Equipment {

// This is the constructor of Weapon
function Weapon(uint atk, uint duration) public {
unique = 0;
}

}
``````

Define Armor similarly:

contract Armor is Equipment {

``````// This is the constructor of Weapon
function Armor(uint atk, uint duration) public {
unique = 1;
}
``````

}

Next, in the atkOrDef function check the attribute against the respective values:

``````function atkOrDef(Equipment equip) returns(int) {
if(equip.getWeaponOrArmor()) return 0;
else 1;
}
``````