language
language copied to clipboard
Type promotion for non-local variables using the is operator
The is
operator in dart can check whether an instance is a type of another type.
int a = 1;
Object b = a;
b is int // true
When using local variables of the type Object
there is automatic type promotion, but when the instance of the object is anything else there is no promotion and the use of the as
operator is needed to cast.
Other languages like C# support casting inside the is
operator.
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/patterns#declaration-and-type-patterns
object greeting = "Hello, World!";
if (greeting is string message)
{
Console.WriteLine(message.ToLower()); // output: hello, world!
}
A feature like this would simplify the code and removes unnecessary lines that don't add anything but clutter.
An example implemenation
int a = 1;
Object b = a;
if (b is int c) {
// within this block c is definced as int
}
This looks like a duplicate of "Binding Cast and Check" in https://github.com/dart-lang/language/issues/1191. There might be other similar proposals too.
Yep. In particular, see:
- https://github.com/dart-lang/language/labels/field-promotion
- #1518
- #1514
- #1420
- #1210
- #1201