language icon indicating copy to clipboard operation
language copied to clipboard

Type promotion for non-local variables using the is operator

Open Sander0542 opened this issue 1 year ago • 1 comments

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
}

Sander0542 avatar Aug 09 '22 19:08 Sander0542

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.

lrhn avatar Aug 09 '22 22:08 lrhn

Yep. In particular, see:

  • https://github.com/dart-lang/language/labels/field-promotion
  • #1518
  • #1514
  • #1420
  • #1210
  • #1201

Levi-Lesches avatar Aug 10 '22 16:08 Levi-Lesches