scala 方法调用_如何在Scala中调用方法N次?

scala 方法调用

Calling a method 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:

在Scala中调用方法 :只需在Scala中使用方法调用来调用函数,但是,可以使用以下两种方法之一来调用方法N次

  1. Using iteration

    使用迭代

  2. Using recursion

    使用递归

1)使用迭代调用方法N次 (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.

n次调用方法的简单逻辑是在运行n次的循环中使用。 并且在每次迭代时,循环都会调用该方法。 因此,相同的方法称为n次。

Example:

例:

Calling a method 5 times that prints "I love includeHelp" using a loop:

调用一个方法5次,并使用循环显示“ I love includeHelp”:

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)使用递归调用方法N次 (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.

调用方法n次的另一种逻辑是使用递归,其中参数作为函数要运行的剩余时间。 在每个调用中,传递的数值减少1,并且在n处遇到1时,函数的递归调用结束。

Example:

例:

Calling a method 5 times that prints "I love includeHelp" using a recursion :

使用递归调用5次打印“ I love includeHelp”的方法:

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


翻译自: https://www.includehelp.com/scala/how-to-call-method-n-times-in-scala.aspx

scala 方法调用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值