Reputation: 97048
I have this code:
void baz(String s) {
}
void bar<T>(T val, void Function(T) encode) {
}
void foo() {
(<String>(val) => bar<String>(val, baz))("foo");
}
However it gives this error:
The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(String)'. dart(argument_type_not_assignable)
A confusing error to say the least! What is going on here?
Upvotes: 1
Views: 171
Reputation: 3229
Dart type parameters are kind of strange since you can use reserved keywords and types as names for these parameters. In this case, <String>(val) => ...
is actually using String
as the name of a type argument in the context of the closure, conflicting with the class String
in dart:core
. If you drop the type argument to your closure in foo
, this code should work and the type of val
in bar
will still be String
. If you want to be sure, you can explicitly type the val
parameter in the closure:
void foo() {
((String val) => bar<String>(val, baz))("foo");
}
Also, the type parameter to bar
can be left out as type inference will be able to infer the type T
is String
:
void foo() {
((String val) => bar(val, baz))("foo");
}
Upvotes: 1