博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
scala 方法调用_如何在Scala中调用方法N次?
阅读量:2529 次
发布时间:2019-05-11

本文共 1899 字,大约阅读时间需要 6 分钟。

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 includeHelpI love includeHelpI love includeHelpI love includeHelpI 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 includeHelpI love includeHelpI love includeHelpI love includeHelpI love includeHelp

翻译自:

scala 方法调用

转载地址:http://egazd.baihongyu.com/

你可能感兴趣的文章
Go 结构体
查看>>
LINQ巩固
查看>>
观看杨老师(杨旭)Asp.Net Core MVC入门教程记录
查看>>
UIDynamic(物理仿真)
查看>>
Windows下安装Redis
查看>>
迷宫实现
查看>>
【字符编码】Java字符编码详细解答及问题探讨
查看>>
学习操作系统导图
查看>>
在线的JSON formate工具
查看>>
winform非常实用的程序退出方法!!!!!(转自博客园)
查看>>
xml解析
查看>>
centos安装vim
查看>>
linux工作调度(计划任务)
查看>>
hdu--1698 Just a Hook(线段树+区间更新+懒惰标记)
查看>>
SynchronousQueue
查看>>
JQuery常用函数及功能小结
查看>>
POJ 2653 Pick-up sticks 线段相交
查看>>
PKU JudgeOnline 题目分类
查看>>
网站报错Access denied for user 'root'@'localhost' -问题排查续
查看>>
字符串处理sdut 2411
查看>>