Skip to content

Strange error when using extension types as generic types #62242

@jellynoone

Description

@jellynoone

This example is analyzed without issues.

void main() {
  final sink = MySink<ExtType<String>>().spying(
    onAdd: (value) {
      print('Spied added value: $value');
    },
  );

  sink.add(ExtType<String>('Hello'));
  sink.add(ExtType<String>('World'));
}

extension type ExtType<T>(T value) {}

abstract interface class MySink<T extends ExtType> {
  void add(T value);

  factory MySink() = _MySink<T>;
}

class _MySink<T extends ExtType> implements MySink<T> {
  @override
  void add(T value) {
    print('Added: $value');
  }
}

extension MySinkExt<T extends ExtType> on MySink<T> {
  MySink<T> spying({required void Function(T value) onAdd}) {
    return _Spying(this, onAdd); // <- missing <T>, causes compile error
  }
}

class _Spying<T extends ExtType> implements MySink<T> {
  final MySink<T> _delegate;
  final void Function(T value) _onAdd;

  _Spying(this._delegate, this._onAdd);

  @override
  void add(T value) {
    _delegate.add(value);
    _onAdd(value);
  }
}

However, when running it, the program doesn't compile. It produces a cryptic compile time error message:

compileNewDDC
main.dart:29:20: Error: The argument type 'MySink<T>' can't be assigned to the parameter type 'MySink<T>'.
 - 'MySink' is from 'package:dartpad_sample/main.dart' ('/tmp/dartpadKTFFEK/lib/main.dart').
    return _Spying(this, onAdd);
                   ^

However, if we manually type out: _Spying<T>, everything works as expected.
This issue is present in all versions of Dart available on DartPad today.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions