linter icon indicating copy to clipboard operation
linter copied to clipboard

Prefer List.of() over List.from() when input and output types are the same

Open jamesderlin opened this issue 5 years ago • 0 comments

AFAIK the difference between List.of() and List.from() (and likewise, Map.of()/Map.from(), Set.of()/Set.from(), and various other collection types) is that .of() takes an argument of the same type as what it returns and enforces it at compilation time, and that .from() allows potentially unsafe downcasting and enforces convertibility at runtime.

This distinction is subtle (and possibly confusing), and I've seen people use .from() unnecessarily, which presumably incurs some additional runtime cost. It'd be nice if there were a lint that recommended using .of() when both the input and output types are the same. (Ideally we also would lint if we can statically determine that the input type is convertible to the output type.)

Examples

var intList = [1, 2, 3];

var copy = List<int>.from(intList); // Lint. Suggest List<int>.of() instead.
var numList = List<num>.from(intList); // Ideally this would generate a lint.

intList = List<int>.from(numList); // OK

var unspecifedList = List.from(intList); // Ideally lint, but can be flagged by [implicit_dynamic_type]

var intSet = Set<int>.from(intList); // Ideally this would generate a lint.

jamesderlin avatar Apr 15 '20 00:04 jamesderlin