Skip to content

Class tannus.ds.Maybe

Ryan Davis edited this page Aug 1, 2015 · 1 revision

abstract Maybe<T> (Null<T>) from Null<T>

The tannus.ds.Maybe type is an abstract type designed to make working with nullable values more tolerable. It allows the user to test for null using field-access, rather than a literal null-check, along with several useful methods for dealing with null values.


Fields


var exists : Bool

If the underlying value is null, then this will be false, whereas with a non-null underlying value, you'll get true.

var value : T

A reference to the underlying value

Methods


function or(value : T):T

If the underlying value is null, returns value, otherwise returns the underlying value

function runIf(func : T->Void):Void

If the underlying value is non-null, invokes func with the underlying value as it's argument

function toBoolean():Bool

Returns whether the underlying value is null


Usage Example


    package ;
    
    import tannus.ds.Maybe;
    
    class Main {
        /**
          * If run with the command-line arguments 'Ryan', 'Davis'
          */
        public static function main():Void {
            var args = Sys.args();
            var first:Maybe<String> = null;
            
            trace(first.exists); // false
            trace(first.or('John')); // 'John'
            //- Or, some syntactic sugar
            trace(first || 'John'); // 'John'
            
            first = args[0];
            
            trace(first.exists); // true
            trace(first.value); // 'Ryan'
            first.runIf(function(name) {
                trace('Hello, $name'); // 'Hello, Ryan'
            });
            
            first = null;
            
            /* Won't Run */
            if (first)
                trace('We has a name');
            
            first = args[0];
            
            /* Will Run */
            if (first)
                trace('We has a name');
        }
    }