Dartz: Using Unit
The dartz package includes classes for programming in a functional style.
Unit
allows you to represent a single return value that doesn't store any information. You may be asking why on earth we'd need this, since we already have void
which does sort-of the same thing?
While the above is true (both void
and Unit
signify the absence of a value), Unit is "void, but better!":
- You no longer have to distinguish between functions that return something (an object) and ones that return nothing (void). All methods can just return
Unit
. - Since
void
isn't actually a type (its more like a keyword), one of the main reasons for usingUnit
is that it makes proper use of the type system. What this means is,Unit
can be used as a type in generics! Unit
is a singleton, therefore any function that returnsUnit.unit
will have exactly the same instance.
Example
As mentioned, one way to use Unit is as a type in a generic:
var authenticationHandler = LoginCommandHandler<LoginCommand, Unit>((command) {
// perform login steps
return Future.value(Unit.unit);
});
If no exceptions occurred during the processing of the LoginCommand
, we can assume that everything is ok.