View source

class thx.Nulls

Available on all platforms

Nulls provides extension methods that help to deal with nullable values.

Note that the parenthesis wrap the entire chain of identifiers. That means that a null check will be performed for each identifier in the chain.

Identifiers can also be getters and methods (both are invoked only once and only if the check reaches them). Python seems to struggle with some native methods like methods on strings.

Class Fields

static function ensure<T>(value:Null<T>, alt:T):Dynamic

Assigns the value alt to value if found null;

static function exists(value:Dynamic):Dynamic

exists is synonymous of notNull.

static function isNull(value:Dynamic):Dynamic

isNull checks if a chain of identifier is null at any point.

static function notNull(value:Dynamic):Dynamic

notNull is the negation of isNull.

static function opt(value:Dynamic):Dynamic

It traverses a chain of dot/array identifiers and it returns the last value in the chain or null if any of the identifiers is not set.

var o : { a : { b : { c : String }}} = null;
trace((o.a.b.c).opt()); // prints null
var o = { a : { b : { c : 'A' }}};
trace((o.a.b.c).opt()); // prints 'A'

static function or<T>(value:Null<T>, alt:T):Dynamic

Like opt but allows an alt value that replaces a null occurrance.

var s : String = null;
trace(s.or('b')); // prints 'b'
s = 'a';
trace(s.or('b')); // prints 'a'

// or more complex
var o : { a : { b : { c : String }}} = null;
trace((o.a.b.c).or("B")); // prints 'B'
var o = { a : { b : { c : 'A' }}};
trace((o.a.b.c).or("B")); // prints 'A'

Notice that the subject value must be a constant identifier (eg: fields, local variables, ...).

static function with<TValue, TOut>(value:TValue, expr:TOut, ?alt:TOut):TOut

Executes expr only if value is a non-null value. Inside expr the value can be referenced using the special var _. It is also possible to provide an alternative value alt in case a non null value is desired.

myvalue.with(_.myMethod());
Toggle inherited fields