scala学习之路:4.for循环递归等函数的使用与多参数的传递

本文介绍了Scala中for循环的使用,包括带条件的循环,并展示了函数的定义与调用,如`addA`和`add`函数。还探讨了递归函数`fac`的实现,以及如何使用`combine`函数传递不同参数。最后讲解了不定参数的使用示例`connected`。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

object dt05_ForFouncation {
  def main(args: Array[String]): Unit = {

   <pre name="code" class="objc">//    1.
    for (i <- 1 to 2; j <- 1 to 2) println(100 * i + j + "")
    //    打印结果
    //101 
    //102
    //201
    //202
    //    2.添加条件表达式
    for (i <- 1 to 2; j <- 1 to 2 if i != j) println(100 * i + j + "")
    //    打印结果
    //102
    //201

    //3. 函数是有返回值的
    def addA(x: Int) = x + 100

    val add = (x: Int) => x + 200

    println("The result from a founcation is :" + addA(2))
    println("The result from a val is :" + add(2))
    //        The result from a founcation is :102
    //        The result from a val is :202

    //4.   递归
    def fac(n: Int): Int = if (n <= 0) 1 else n * fac(n - 1)
    println("The result from a fac is :" + fac(6))
    //The result from a fac is :720

    //    5.传递多个不同的参数
    def combine(content: String, left: String = "[", right: String = "]") = left + content + right
    println("The result from a combine is :" + combine("I love spark", ">"))
    //    The result from a combine is :>I love spark]

    //    6.

    def connected(args: Int*) = { // 不定参数的使用类似于java中的

      var result = 0
      for (arg <- args) result += arg

      result

    }
    println("The result from a connected is :" + connected(1, 2, 3, 5, 7))
    
    //The result from a connected is :18


}
}


                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值