Is this normal behavior or am I missing something?

28 views
Skip to first unread message

Andrew Mezoni

unread,
May 25, 2021, 2:49:43 PM5/25/21
to Dart Misc
The code compiles and runs fine, but throws an exception. 
Is that how it should be?

void main() {
  final c = LC<String>('foo');
  // CP want c<List<int>?, T> but c is C<List<int>, T>
  final cp = CP<List<int>?, String>(c);
  cp.p(null);
}

abstract class C<I, O> {
  O c(I v);
}

class CP<I, T> {
  final C<I, T> c;

  CP(this.c);

  T p(I v) => c.c(v);
}

class LC<T> implements C<List<int>, T> {
  final T v;

  LC(this.v);

  @override
  // Unhandled exception:
  // type 'Null' is not a subtype of type 'List<int>' of 'v'
  T c(List<int> v) => this.v;
}

Lasse R.H. Nielsen

unread,
May 25, 2021, 3:05:34 PM5/25/21
to mi...@dartlang.org
Yes, that's expected behavior (if I read the example correctly).

Dart's covariant generics are unsound, which is why methods parameters typed with the type arguments get run-time checks added.
It's the same issue as:

  List<int?> list = <int>[];
  list.add(null); // run-time error.

/L

--
For more ways to connect visit https://dart.dev/community
---
You received this message because you are subscribed to the Google Groups "Dart Misc" group.
To unsubscribe from this group and stop receiving emails from it, send an email to misc+uns...@dartlang.org.
To view this discussion on the web visit https://groups.google.com/a/dartlang.org/d/msgid/misc/c14275c8-32ca-445d-afc3-3edf140681ebn%40dartlang.org.


--
Lasse R.H. Nielsen - l...@google.com  
'Faith without judgement merely degrades the spirit divine'
Google Denmark ApS - Frederiksborggade 20B, 1 sal - 1360 København K - Denmark - CVR nr. 28 86 69 84

Andrew Mezoni

unread,
May 25, 2021, 3:11:08 PM5/25/21
to Dart Misc, Lasse Reichstein Holst Nielsen
Yeah...
Thank you.


среда, 26 мая 2021 г. в 00:05:34 UTC+5, Lasse Reichstein Holst Nielsen:

Andrew Mezoni

unread,
May 25, 2021, 3:42:43 PM5/25/21
to Dart Misc, Andrew Mezoni, Lasse Reichstein Holst Nielsen
You have to add rule to the linter for such cases.
For Lists.

 List<int?> list = <int>[]; // <= Some warning about possible unpredictable behavior at runtime.
среда, 26 мая 2021 г. в 00:11:08 UTC+5, Andrew Mezoni:
Reply all
Reply to author
Forward
0 new messages