Dart specification states:
Reified type information reflects the types of objects at runtime and may always be queried by dynamic typechecking constructs (the analogs of instanceOf, casts, typecase etc. in other languages).
Sounds great, but there is no instanceof
-like operator. So how do we perform runtime type-checking in Dart? Is it possible at all?
There are two operators for type testing:
E is T
tests for E an instance of type T whileE is! T
tests for E not an instance of type T.Note that
E is Object
is always true, andnull is T
is always false unlessT===Object
.The instanceof-operator is called
is
in Dart. The spec isn't exactly friendly to a casual reader, so the best description right now seems to be http://www.dartlang.org/articles/optional-types/.Here's an example:
Dart
Object
type has aruntimeType
instance member (source is fromdart-sdk
v1.14, don't know if it was available earlier)Usage:
object.runtimeType
returns the type of objectFor example:
As others have mentioned, Dart's
is
operator is the equivalent of Javascript'sinstanceof
operator. However, I haven't found a direct analogue of thetypeof
operator in Dart.Thankfully the dart:mirrors reflection API has recently been added to the SDK, and is now available for download in the latest Editor+SDK package. Here's a short demo:
Just to clarify a bit the difference between
is
andruntimeType
. As someone said already (and this was tested with Dart V2+) the following code:will output:
Which is wrong. Now, I can't see the reason why one should do such a thing...