H.org
  • Questions

Dartz: Using Unit

  1. dartz
  2. dart
  3. functional-programming

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 using Unit 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 returns Unit.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.

Ko-Fi button Support Me on Ko-fi

Created with lots of green tea and 11ty

Opinions are solely my own and not those of my employer.

Privacy Policy - Licenses