Dart: how to return value from calling a recursive function?
How do I return the value from a recursive function?
I know how to pass a value to a function and return a value:
void main(){
Halfer(myNumber) {
myNumber = myNumber~/2;
return myNumber;
};
var myNumber = 99;
print(Halfer(myNumber));
}
That prints 49
to the console.
The following code prints a single digit value to the console:
void main(){
SingleDigitizer(myNumber) {
if (myNumber > 9) {
myNumber = myNumber~/10;
SingleDigitizer(myNumber);
} else {
print(myNumber);
}
};
var myNumber = 99;
SingleDigitizer(myNumber);
}
The result 9
prints to the console.
The next program doesn't work. It prints null
to the console:
void main(){
SingleDigitizer(myNumber) {
if (myNumber > 9) {
myNumber = myNumber~/10;
SingleDigitizer(myNumber);
} else {
return myNumber;
}
};
var myNumber = 99;
print(SingleDigitizer(myNumber));
}
How do I return the value from a recursive function?
Solution 1:
The best solution would be to define some types, at least the return type of the SingleDigitizer
method (which should also be written in lower case).
If you tell the compiler that SingleDigitizer
returns an int
, it will help you to find your mistake ;-)
Hint: The if
block has no return
statement, the else
block does.
Solution 2:
Two methods:
- Return from internal calling function
void main(){
SingleDigitizer(myNumber) {
if (myNumber > 9) {
myNumber = myNumber~/10;
return SingleDigitizer(myNumber);
} else {
return myNumber;
}
};
var myNumber = 99;
print(SingleDigitizer(myNumber));
}
Notice the return
in line 6.
- Set up variable to assign the value
void main(){
var result;
SingleDigitizer(myNumber) {
if (myNumber > 9) {
myNumber = myNumber~/10;
SingleDigitizer(myNumber);
} else {
result = myNumber;
}
};
SingleDigitizer(99);
print(result);
}