Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

multiplying 2 int types results in a num type

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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));

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading