Home > Back-end >  Pow() function giving error regarding data types
Pow() function giving error regarding data types

Time:04-29

import 'dart:math';

void main (){
    int num = 235;
    var numToString = num.toString();
    var result = numToString.split('').map(int.parse).reduce((t,e)=>pow(t,t) pow(e,e));
    print(result);
}

I am trying to solve a problem that wants me to check if the number is an Armstrong Number or not. I have tried to read the documentation but was unable to really work out the issue.

Error: A value of type 'num' can't be returned from a function with return type 'int'.
    var result = numToString.split('').map(int.parse).reduce((t,e)=>pow(t,t) pow(e,e));

Appreciate your help. Thanks.

CodePudding user response:

As indicated by the pow documentation, pow is declared to return a num, so that's the static type known to the compiler. Depending on its arguments, that num could actually be an int or a double at runtime (which the compiler will not know about):

If x is an int and exponent is a non-negative int, the result is an int, otherwise both arguments are converted to doubles first, and the result is a double.

Meanwhile, your call to reduce operates on a List<int> and therefore expects int arguments.

If you can logically guarantee that the first argument is an int and that the second argument is non-negative (which you can in this case), you can safely cast the result of pow to an int:

import 'dart:math';

void main() {
  int num = 235;
  var numToString = num.toString();
  var result = numToString
      .split('')
      .map(int.parse)
      .reduce((t, e) => (pow(t, t)   pow(e, e)) as int);
  print(result);
}

Alternatively, if you want to store arbitrary numbers and not just integers, you can use List<num> instead of List<int> by giving an explicit type argument to .map instead of letting it be inferred from int.parse:

import 'dart:math';

void main() {
  int number = 235;
  var numToString = number.toString();
  var result = numToString
      .split('')
      .map<num>(int.parse)
      .reduce((t, e) => pow(t, t)   pow(e, e));
  print(result);
}

Note that the above also requires renaming your local num variable to avoid colliding with the num type.

(By the way, the documentation you linked to is rather old (it's from the Dart 1 SDK!). You should always refer to the latest SDK documentation (or to documentation for the SDK version you have).)

  •  Tags:  
  • dart
  • Related