26

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?

MendelG
  • 14,885
  • 4
  • 25
  • 52
himekami
  • 1,419
  • 3
  • 13
  • 21

6 Answers6

22

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.)

jamesdlin
  • 81,374
  • 13
  • 159
  • 204
7

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

martinseal1987
  • 1,862
  • 8
  • 44
  • 77
4

As the language tour says:

Use the as operator to cast an object to a particular type if and only if you are sure that the object is of that type.

Following with your example:

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

You would use as here to cast or convert json['images'] into a <List> object.

Mayank
  • 1,595
  • 1
  • 11
  • 26
2

From another SO post (talking about explicit cast vs. as):

as ... is more like an assertion, if the values type doesn't match as causes a runtime exception.

You can also use it when importing packages. A common example is the dart:convert as JSON which then can be reached final foo = JSON.jsonDecode(baz)

flarkmarup
  • 5,129
  • 3
  • 24
  • 25
2

It's casting, your code is similar as:

List list = json['images'];

apieceofcode1801
  • 171
  • 1
  • 1
  • 9
0

Also the "as" keyword is really good for adding context around naked functions. This improves readibility by making it easier to differentiate which functions were imported versus which ones were created locally.

For example the function getTemporaryDirectory from the path_provider package is imported and used like shown below:

    import 'package:path_provider/path_provider.dart'
.
.
.
      final directory = await getTemporaryDirectory();

The same code can be called and used like this:

    import 'package:path_provider/path_provider.dart' as path;
.
.
.

    final directory = await path.getTemporaryDirectory();

The latter makes it more clear that this is an import function and not one sourced locally