Skip to content

Commit

Permalink
feat: add cast_utils.dart (castAsOrNull, castAsNullable)
Browse files Browse the repository at this point in the history
  • Loading branch information
alextekartik committed Dec 11, 2023
1 parent 0a96fc7 commit d976e39
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/src/cast_utils.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
/// Future compat to always return nullable.
T? castAsNullable<T extends Object>(T? value) => value;
T? castAsNullable<T extends Object?>(T? value) => value;

/// Safe cast
T? castAsOrNull<T extends Object>(Object? object) =>
T? castAsOrNull<T extends Object?>(Object? object) =>
object is T ? object : null;
2 changes: 1 addition & 1 deletion pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name: tekartik_common_utils
version: 0.15.2
version: 0.15.2+1
description: Common pure dart utilities (not io or browser dependant)
homepage: https://github.com/tekartik/common_utils.dart
publish_to: none
Expand Down
5 changes: 5 additions & 0 deletions test/cast_utils_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ void main() {

group('cast_utils', () {
test('castAsNullable', () {
expect(castAsNullable<int>(null), isNull);
expect(castAsNullable<int>(1), 1);
expect(castAsNullable<int?>(null), isNull);

void nullableFunction(int? value) {}
void nonNullFunction(int value) {}
nonNullableInt = 1;
Expand All @@ -23,6 +27,7 @@ void main() {
expect(castAsOrNull<int>(1), 1);
expect(castAsOrNull<int>('1'), isNull);
expect(castAsOrNull<int>(null), isNull);
expect(castAsOrNull<int?>(null), isNull);
});
});
}

0 comments on commit d976e39

Please sign in to comment.