Home > Back-end >  type error when using list variable instead of direct list in dart
type error when using list variable instead of direct list in dart

Time:11-08

I'm learning the dart language, and I encountered this problem with lists. i created a sum function to calculate the sum of 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 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 boought types double and int, but i can't understand the problem that raises when i use a middle variable?? any explanation please. thnks in advance.

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