Created
March 4, 2023 04:07
-
-
Save mykhailokrainik/b7f802478f2e37504ccff7497a83be39 to your computer and use it in GitHub Desktop.
Implement Rust’s Result Type in Dart (https://misha-krainik.medium.com/how-to-implement-rusts-result-type-in-dart-programming-language-df96ad3c7115)
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
enum Error { | |
recordNotFound, | |
notValidId, | |
} | |
class Result<T, E> { | |
T? value; | |
E? error; | |
Result.Ok(T value) { | |
this.value = value; | |
} | |
Result.Err(E error) { | |
this.error = error; | |
} | |
dynamic then({required Function ok, required Function err}) { | |
if (this.value != null) { | |
return ok(value); | |
} | |
if (this.error != null) { | |
return err(error); | |
} | |
} | |
} | |
class Record { | |
int _id; | |
get getId => _id; | |
Record({required id}) : _id = id; | |
String toString() => 'Record(id: $_id)'; | |
} | |
class RecordStore { | |
final _records; | |
RecordStore({required records}) : _records = records; | |
Result<Record, Error> getRecordById(int searchId) { | |
if (searchId <= 0) return Result.Err(Error.notValidId); | |
for (final record in _records) { | |
if (record.getId == searchId) return Result.Ok(record); | |
} | |
return Result.Err(Error.recordNotFound); | |
} | |
} | |
void main() { | |
final store = RecordStore( | |
records: List<Record>.generate(10, (genNum) => Record(id: genNum))); | |
final result = store.getRecordById(-4); | |
result.then(ok: (record) { | |
print(record.toString()); | |
}, err: (error) { | |
switch (error) { | |
case Error.recordNotFound: | |
print("Nothing to display at this time."); | |
break; | |
case Error.notValidId: | |
print( | |
"Invalid ID provided. Please enter a positive integer value for the record ID."); | |
} | |
}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment