Advertisement
Hiteshw11

Calculate Sum Of All Elements in List using Generic Methods

Nov 27th, 2024
41
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 0.35 KB | Source Code | 0 0
  1. /* Create a generic method `calculateSum` that takes a list of numbers and returns the sum */
  2.  
  3.  
  4.  
  5. void main() {
  6.   var a = One();
  7.    print(a.calculateSum([1,2,3,4,5]));
  8. }
  9.  
  10.  
  11. class One
  12. {
  13.  
  14. One();
  15.  
  16.  
  17. T calculateSum<T extends num>(List<T> list1)
  18. {
  19.  
  20. num sum1=0;
  21.  
  22. for(var element in list1)
  23. {
  24.  
  25. sum1=(element+sum1);
  26. }
  27.  
  28.  
  29. return sum1 as T;
  30. }
  31.  
  32.  
  33. }
Tags: dart
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement