Skip to content

Assignability of generic type Never #3670

@SandroMaglione

Description

@SandroMaglione

I noticed that the Never type seems to be assignable to any other type when working with generics:

class Obj<A> {
  const Obj();
}

final val = Obj<Never>();

void fun(Obj<String> obj) {}

void main() {
  fun(val); // 👈 No error here when Obj<Never> passed to Obj<String>
}

I would expect calling fun with val to error at compile time, since Obj<Never> cannot be assigned to Obj<String>.

In my specific case I am using Never to express a "missing"/"not possible" value (reference), and this breaks at compile time in cases like below:

class Obj<A> {
  const Obj();
  
  void execute(A a) {}
}

final val = Obj<Never>();

void fun(Obj<String> obj) {
  obj.execute("abc"); // 👈 `String` not `Never`
}

void main() {
  fun(val);
}

Is this the correct/expected behaviour?

Note: In my usecase would void be preferable to Never?

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions