Home > Software design >  Dart - Recursive function returning null
Dart - Recursive function returning null

Time:09-17

I am trying to create a simple recursive function which generates a random number between 0 & 4 and this generated number should not be equal to 'correctIndex'.

random(min, max) {
   var rn = new Random();
   int ans = 0;
   ans = (min   rn.nextInt(max - min));
   if (ans == correctIndex) {
     print("Recursive $ans $correctIndex");
     random(0, 4);
   } else {
     print("Correct Index $correctIndex 5050 $ans");
     return ans;
   }
 }

And I am calling the above function as follows:

setState(() {
  randomIndex = random(0, 4);
});
print("output value of $randomIndex");

The times when recursive part isn't called 'randomIndex' has a value. But anytime the recursive part is called, the randomIndex has value of null even though the function is returning a value. Following is the output from debug console when recursive is called

I/flutter ( 5071): Recursive 2 2
I/flutter ( 5071): Correct Index 2 5050 3
I/flutter ( 5071): output value of null

Following is the output if no recursive was called:

I/flutter ( 5071): Correct Index 2 5050 1
I/flutter ( 5071): output value of 1

Can someone please guide me as to what I am doing wrong. Thank you in advance.

CodePudding user response:

This code is equivalent to:

random(min, max) {
   var rn = new Random();
   int ans = 0;
   ans = (min   rn.nextInt(max - min));
   if (ans == correctIndex) {
     print("Recursive $ans $correctIndex");
     random(0, 4);
   } else {
     print("Correct Index $correctIndex 5050 $ans");
     return ans;
   }
   return null; // <-- NOTE! dart (flutter) will auto do this.
 }

Thus, when if is true, you will return null finally!

So maybe you want random(0, 4); become return random(0,4)?

  • Related