Open SEAFromJahu opened 2 years ago
The Dart compiler does not assume that there are no further classes implementing Animal
, so it doesn't know that there is no chance of reaching the return null;
. (Even if it did know that, the flow analysis wouldn't be smart enough to use it.)
The problem with Animal funcao(Animal toto) { ... }
is that you need to return an Animal
on every path.
Returning null
and returning nothing (which effectively returns null
) are not options if the return type is not nullable.
You have to do something else.
What you can do instead is to throw as the third option:
Animal funcao(Animal toto) {
if (toto is Cachorro) {
// ...
return Cachorro(toto.nome, toto.idade);
} else if (toto is Gato) {
// ...
return Gato(toto.nome, toto.idade);
}
throw ArgumentError.value(toto, "toto", "Unknown animal");
// or: throw UnsupportedError("Unknown animal: $toto");
}
If the only two animals your program contains are Cochorro
and Gato
, then the code will never reach the throw
, but it being there will make the compiler happy by not trying to return null
.
Another alternative would be:
Animal funcao(Animal toto) {
if (toto is Cachorro) {
// ...
return Cachorro(toto.nome, toto.idade);
}
Gato gato = toto as Gato;
// ...
return Gato(gato.nome, gato.idade);
}
It's basically the same, you just get an error at the cast if toto
is neither Cochorro
or Gato
.
Include a permanent link to the error if possible.
https://help.github.com/en/articles/getting-permanent-links-to-files