Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference fails on switch expression but works on switch statement #3477

Closed
renatoathaydes opened this issue Nov 21, 2023 · 1 comment
Closed
Labels
request Requests to resolve a particular developer problem

Comments

@renatoathaydes
Copy link

renatoathaydes commented Nov 21, 2023

This code does not compile:

import 'dart:convert';

class IntConverter extends Converter<String, int> {
  @override
  int convert(String s) => int.parse(s);
}
class DoubleConverter extends Converter<String, double> {
  @override
  double convert(String s) => double.parse(s);
}

Converter<Object?, Object?>? selectConverter(String name) {
  // OK
  Converter<Object?, Object?> c1 = IntConverter();
  // OK
  Converter<Object?, Object?> c2 = DoubleConverter();
  // NOT OK: 
  return switch(name) {
      'int' => IntConverter(),
      'double' => DoubleConverter(),
      _ => null,
  };
}

The error says:

A value of type 'Object?' can't be returned from the function 'selectConverter' because it has a return type of 'Converter<Object?, Object?>?'.

However, as c1 and c2 show, the types should check.

Indeed, with a switch statement it works:

Converter<Object?, Object?>? selectConverter(String name) {
  switch(name) {
    case 'int': return  IntConverter();
    case 'double': return DoubleConverter();
    default: return null;
  }
}

It's a minor inconvenience, of course, but hopefully can be fixed.

@renatoathaydes renatoathaydes added the request Requests to resolve a particular developer problem label Nov 21, 2023
@leafpetersen
Copy link
Member

I believe this is an example of this issue (see my comment as of March 31). There is work in progress to address this. cc @stereotype441

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

2 participants