Created
September 29, 2025 07:52
-
-
Save TesteurManiak/510271eb8b20552d04510b4d066b297b to your computer and use it in GitHub Desktop.
Dart implementation of Swift's Optional type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import 'package:meta/meta.dart'; | |
| /// Dart implementation of Swift's `Optional` type. | |
| /// | |
| /// {@template optional} | |
| /// Creates an object that holds a nullable value which can be unwrapped | |
| /// safely. | |
| /// {@endtemplate} | |
| /// | |
| /// Swift specs: https://developer.apple.com/documentation/swift/optional | |
| @immutable | |
| final class Optional<Wrapped extends Object> { | |
| /// {@macro optional} | |
| const Optional(this.value); | |
| /// Creates an [Optional] object that holds a non-null value. | |
| const Optional.some(Wrapped this.value); | |
| /// Creates an [Optional] object that holds a null value. | |
| const Optional.none() : value = null; | |
| final Wrapped? value; | |
| /// {@template optional_map} | |
| /// Evaluates the given closure when this [Optional] instance is not null, | |
| /// passing the unwrapped [value] as a parameter. | |
| /// {@endtemplate} | |
| U? map<U>(U Function(Wrapped value) cb) { | |
| return switch (value) { | |
| final value? => cb(value), | |
| null => null, | |
| }; | |
| } | |
| /// {@macro optional_map} | |
| Optional<U> flatMap<U extends Object>(Optional<U> Function(Wrapped value) cb) { | |
| return switch (value) { | |
| final value? => cb(value), | |
| null => const Optional.none(), | |
| }; | |
| } | |
| @override | |
| bool operator ==(Object other) => other is Optional<Wrapped> && other.value == value; | |
| @override | |
| int get hashCode => Object.hash(runtimeType, value); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment