Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, syntactically nice way to cast dynamic to given type or return null?

Tags:

dart

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?

like image 423
Andrey Mishchenko Avatar asked Oct 03 '18 16:10

Andrey Mishchenko


People also ask

Can dynamic Darts be null?

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.

What is dynamic data type in Dart?

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.

What is the difference between dynamic and object in Dart?

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.


2 Answers

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

like image 162
Günter Zöchbauer Avatar answered Oct 07 '22 08:10

Günter Zöchbauer


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'); 
like image 39
Magnus Avatar answered Oct 07 '22 10:10

Magnus