Home > other >  Type error when using List<int> variable as an argument to a List<double> method paramet
Type error when using List<int> variable as an argument to a List<double> method paramet

Time:11-10

I'm learning the dart language, and I encountered this problem with lists. I created a sum function to calculate the sum of a list, here is the code:

double sum(List<double> elements) {
   var el = 0.0;
   for (var elem in elements) {
      el  = elem;
   }
   return el;
}

And I call it from the main menu in 2 ways:

void main(List<String> args) {
   var sm = sum([1, 3, 4, 6]);
   print(sm)
}

And it worked fine. But when I try to use a middle variable:

var test = [1, 3, 4, 6];
var sm = sum(test);
print(sm);

I get an error :

 Error: The argument type 'List<int>' can't be assigned to the parameter type 
 'List<double>'.
 functions.dart:5
 - 'List' is from 'dart:core'.
   var sm = sum(test);
                ^

I know that i have to use List as i'm using list of int but it appears that that function I made could work with both types, double and int, but i can't understand the problem when I use a middle variable?

CodePudding user response:

In your first example the list of int literals is automatically converted to double, which is a new feature of Dart 2.1. (source) - int literals get converted automatically to doubles in a double context:

var sm = sum([1, 3, 4, 6]);

Before that, you would experience a compilation error and would have to explicitly provide a double list as a parameter:

var sm = sum([1.0, 3.0, 4.0, 6.0]);

On your second example however, you are implicitly defining a List<int> variable, which cannot be passed as a List<double> parameter.

  •  Tags:  
  • dart
  • Related