Is it possible to create a loop that calls a method every time it finishes executing? I would like to continually call the same method every time it finishes executing.
I am a beginner and I have only seen loops that work every x time but I don't know if it is possible to do this.
CodePudding user response:
You could achieve this using something like the following:
fun loop(){
var counter = 0
var run = true
while(run){
counter
if(counter > 100)
run = false
// call method here
}
}
This will call a method 100 times. When you remove the run parameter, and place while(true)
, the code will run infinitely. This is not recommended however.
CodePudding user response:
Yes, you can use recursion. Recursion is often used to break down big problems to smaller ones calling the same method within it's body. Here is an example in kotlin
fun main(args: Array<String>) {
val number = 5
val result: Long
result = factorial(number)
println("Factorial of $number = $result")
}
fun factorial(n: Int): Long {
return if(n == 1){
n.toLong()
}
else{
n*factorial(n-1)
}
}
In this example we calculate the factorial of a given number with the recursive function. To break it down even more, it looks like this.
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120