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?
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 import
ed library to avoid name collisions. (as
was reused to do different things to avoid needing extra keywords.)
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
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.
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)
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