Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "as" keyword do in Dart language

Tags:

flutter

dart

I'm confused as to the uses of "as" keyword.

Is it a cast operator or alias operator ?

I encountered the following code on the internet which looked like a cast operator:

var list = json['images'] as List;

What does this mean?

like image 651
himekami Avatar asked Apr 22 '19 04:04

himekami


People also ask

What is the as keyword used for in Dart?

2. as:- as operator is used to cast an object to a particular type if and only if when we are sure that the object is of that type. Example: Dart.

What is new keyword in Dart?

The new keyword is used to create an instance of a class. However, Dart 2 makes the new keyword optional. Calling a class will always return a new instance of that class.

Is new keyword optional in Dart?

No, it does not.

What is == in Dart?

Dart supports == for equality and identical(a, b) for identity. Dart no longer supports the === syntax. Use == for equality when you want to check if too objects are "equal". You can implement the == method in your class to define what equality means.


2 Answers

as means different things in different contexts.

It's primarily used as a type cast operator. From the Dart Language Tour:

as: Typecast (also used to specify library prefixes)

It links to an explanation of how as is also used to add a prefix to an imported library to avoid name collisions. (as was reused to do different things to avoid needing extra keywords.)

like image 134
jamesdlin Avatar answered Sep 23 '22 05:09

jamesdlin


just to add the as keyword is now flagged by the linter and they prefer you to use a check like is

if (pm is Person)
  pm.firstName = 'Seth';

you can read more here https://github.com/dart-lang/linter/issues/145

like image 21
martinseal1987 Avatar answered Sep 26 '22 05:09

martinseal1987