An 'as?' operator

29 views
Skip to first unread message

Stan Manilov

unread,
Nov 2, 2017, 11:12:37 AM11/2/17
to Dart Core Development
From a user's perspective, I want to cast an object to a type, and get a null if the object is not of that type. Then I can use the ?. operator to get a member out of the object, in case of success, or null otherwise. To me, it is natural to express this in the following way:

MemberType get extractedMember => (object as? Type)?.member;

This, of course, is wishful thinking, since there is no 'as?' operator. Currently, the best way to express this is (parenthesis subject to taste, formatting as per dartfmt):

MemberType get extractedMember => (object is Type)
    ? (object as Type).member
    : null;

Putting aside for a moment the amount of work to the dev tools necessary to support such feature, I am wondering if there any problems with it from language perspective?

Thanks,
 - Stan

Bob Nystrom

unread,
Nov 2, 2017, 11:31:55 AM11/2/17
to Stan Manilov, Dart Core Development
I don't see any problems. It doesn't look ambiguous to me since "as" currently always requires an operand on the right and "?:" always requires on the left so, "as?" shouldn't collide with the existing grammar.

The behavior you describe is often the one I wish the normal "as" operator had. (It's also how "as" works in C#.)

Assuming we get non-nullable types, an "as?" operator might get a little confusing and awkward to use but it could work out OK. I'd have to think about it.

Cheers!

– bob

Stan Manilov

unread,
Nov 8, 2017, 7:26:03 AM11/8/17
to Bob Nystrom, Dart Core Development
Hi Bob,

Thanks for the reply.

Regarding your last point: initially I wasn't sure how "as?" would be any more confusing than "?." for non-nullable types, but now I think I get it. If Type is non-nullable and NullableType is it's corresponding, ehm, nullable type, then (object as? Type) would have type NullableType, where the confusion comes from, correct? Perhaps "as?" should be (statically) forced to take only nullable types as its second argument to avoid such a confusion, whereas just "as" can take non-nullable types too and throw an exception if the cast fails (as it already does).

In a related note, I just checked what (null as Type) does, and it seems to be just null (which is not confusing, but it's not exactly obvious). Then if the result of (object as? Type) is null, that can mean two different things: object is null or object is not of type Type (or even both, if Type is non-nullable!), so that might be a problem for the user.

Let me know if I'm taking this too far :)

Cheers,
 - Stan


Reply all
Reply to author
Forward
0 new messages