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?