Home > front end >  multiplying 2 int types results in a num type
multiplying 2 int types results in a num type

Time:03-18

I'm currently studying Dart and practicing what I learned by doing coding challenges at codewars.com.

One of the basic challenges that I'm trying to solve is to create a function that will convert a binary string to its decimal equivalent.

The initial solution (albeit, not optimal) that I wrote involved the following code:

int binToDec(bin) {
  int dec = 0;
  for (int i = bin.length-1, j = 0; i >= 0; i--, j  ) {
    
    dec  = (int.parse(bin[i]) * pow(2, j));
  }
  return dec;
}

Running the code though (whether in codewars.com or DartPad) will give out the following error:

Error: A value of type 'num' can't be assigned to a variable of type 'int'.
    dec  = (int.parse(bin[i]) * pow(2, j));
        ^

I was able to fix this by adding a toInt() method to the right side of the equation:

dec  = (int.parse(bin[i]) * pow(2, j)).toInt();

My question is, why did the compiler mention that I'm assigning a num type value to the 'dec' variable when the runtimeType of (int.parse(bin[i]) * pow(2, j)) is an int type?

i.e.:

print((int.parse(bin[i]) * pow(2, j)).runtimeType);

would print the following result in the Dartpad console:

int

CodePudding user response:

My question is, why did the compiler mention that I'm assigning a num type value to the 'dec' variable when the runtimeType of (int.parse(bin[i]) * pow(2, j)) is an int type?

Because the compiler doesn't know what the runtime type is. The runtime type, by definition, is known at runtime.

pow is declared to return a num, so that's the type known at compile-time. Depending on the arguments given (see the documentation), pow can return an int at runtime, but it's impractical for the compiler to know for what combinations of arguments pow returns int and for what combinations it returns double. You therefore must cast its result when you know what to expect: dec = (int.parse(...) * (pow(2, j) as int));

  •  Tags:  
  • dart
  • Related