I have a dynamic x
and I would like to assign x
to T s
if x is T
, and otherwise assign null
to s
. Specifically, I would like to avoid having to type x
twice, and to avoid creating a temporary. (For example, I don't want to have to write String s = map['key'] is String ? map['key'] : null;
over and over, because I will have many such expressions.) I don't want there to be any possibility of a runtime error.
The following works:
class Cast<T> { T f(x) { if (x is T) { return x; } else { return null; } } } // ... dynamic x = something(); String s = Cast<String>().f(x);
Is there a syntactically nicer way to do this?
The dynamic type is inherently nullable, adding ? to it makes no difference, just as Null? is meaningless. The Dart type system is statically null sound (mostly, the usual caveats around generics apply), but dynamic is a way to turn that type system off on request. Don't use dynamic unless you want that effect.
Dart dynamic type In Dart, when a variable is declared as a dynamic type, it can store any value, such as int and float . The value of a dynamic variable can change over time within the program.
There is actually no difference between using Object and dynamic in the example you have given here. There is no practical difference, and you can swap the two and the program will run the same. When I refer to "semantic difference", I mean how the code will be understood by other Dart programmers.
Dart 2 has generic functions which allows
T? cast<T>(x) => x is T ? x : null;
dynamic x = something(); String s = cast<String>(x);
you can also use
var /* or final */ s = cast<String>(x);
and get String
inferred for s
I use the following utility function, which allows for an optional fallback value and error logging.
T tryCast<T>(dynamic x, {T fallback}){ try{ return (x as T); } on CastError catch(e){ print('CastError when trying to cast $x to $T!'); return fallback; } }
var x = something(); String s = tryCast(x, fallback: 'nothing');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With