Error: The operator '+' isn't defined for the class 'Object?'

Viewed 258

I am having a challenge folding a list of integer elements to sum them up.

 List<int> ints = [1,2,3,4,5];
 var result = ints.fold(0, (pV,element)=>pV + element);
 print(result);

Somehow I can't get this simple code to compile. I keep getting the error:

Error compiling to JavaScript:
Warning: Interpreting this as package URI, 'package:dartpad_sample/main.dart'.
lib/main.dart:19:46:
Error: The operator '+' isn't defined for the class 'Object?'.
 - 'Object' is from 'dart:core'.
var result = ints.fold(0, (pV,element)=>pV + element);
                                         ^
Error: Compilation failed.

Any help

2 Answers

I don't know why, but if you are explicit with the types, it works:

var result = ints.fold(0, (int pV, element) => pV + element);

As pV is of type object and element is of type int, you cannot add them.

You can do something like this if you required:

List<int> ints = [1,2,3,4,5];
 var result = ints.fold(0, (pV,element)=>int.parse(pV.toString()) + element);
 print(result);
Related