Home »
Scala
How to call method N times in Scala?
By IncludeHelp Last updated : October 20, 2024
Two ways to call method N times in Scala
Simply call the function using a method call in Scala, but, calling method N times can be done using either of the two ways:
- Using iteration
- Using recursion
1. Calling method N times using iteration
A simple logic to call a method n times is using on a loop that runs n times. And at each iteration, the loop calls the method. So, the same method is called n times.
Example
Calling a method 5 times that prints "I love includeHelp" using a loop:
object MyClass {
def printStatement(){
println("I love includeHelp");
}
def main(args: Array[String]) {
val n = 5;
for(i <- 1 to n){
printStatement();
}
}
}
Output
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
2. Calling method N times using recursion
Another logic to call a method n times is using recursion, with parameter as the remaining numbers of time the function is to be run. At each call, the number value passed is decreased by one and the function's recursive call ends when 1 is encounters at n.
Example
Calling a method 5 times that prints "I love includeHelp" using a recursion :
object MyClass {
def printStatement( n: Int){
println("I love includeHelp");
if(n!= 1 ){
printStatement(n-1);
}
}
def main(args: Array[String]) {
val n = 5;
printStatement(n);
}
}
Output
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp
I love includeHelp