Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add an as() for null-safety casting similar to as? in Kotlin #37

Closed
yongjhih opened this issue Jan 13, 2020 · 1 comment
Closed

Add an as() for null-safety casting similar to as? in Kotlin #37

yongjhih opened this issue Jan 13, 2020 · 1 comment

Comments

@yongjhih
Copy link
Contributor

yongjhih commented Jan 13, 2020

T as<T>(dynamic it) => it is T ? it : null; // that's what I used for a long time.

  test('should as<T>()', () async {
    const dynamic it = "Hello";
    expect(as<String>(it) ?? "", "Hello");
    expect(as<int>(it) ?? 0, 0);
    const nullIt = null;
    expect(as<String>(nullIt) ?? "", "");
  });

I tried to implement it with the following code, but they don't work, I think it's a limitation in Dart:

extension NullableObject on Object {
  R as<R>() => this is R ? this as R : null;
}

or

extension NullableDynamic on dynamic {
  R as<R>() => this is R ? this as R : null;
}
@yongjhih yongjhih changed the title Add an Object.as() for null-safety casting similar to as? in Kotlin Add an as() for null-safety casting similar to as? in Kotlin Jan 13, 2020
@yongjhih
Copy link
Contributor Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant