Optionals are variables or struct fields that can be null and don't necessarily hold a value. They are useful to reduce state size when the variable isn't necessarily used.
You can make any variable optional by adding ?
after its type.
Optional variables that are not defined hold the null
value. You cannot access them without checking for null
first.
If you're certain an optional variable is not null, append to the end of its name !!
to access its value. Trying to access the value without !!
will result in a compilation error.
// this trait has to be imported import "@stdlib/ownable"; import "@stdlib/deploy"; // the Ownable trait can limit certain actions to the owner only contract Counter with Deployable, Ownable { owner: Address; // The Ownable trait requires you to add this exact state variable val: Int as uint32; init() { self.owner = sender(); // we can initialize owner to any value we want, the deployer in this case self.val = 0; } // this message is available to anyone receive("increment") { self.val = self.val + 1; } // this message in only available to the owner receive("double") { self.requireOwner(); self.val = self.val * 2; } get fun value(): Int { return self.val; } // get fun owner(): Address is added automatically to query who the owner is }