Scala-函数

1、定义函数

object helloworld {

  def main(args: Array[String]) {
    //定义函数
    def add(a:Int,b:Int):Int = {
      var c = a + b;
      return c;
    }
    print(add(1,2));
  }
}


---不写返回值 return
object helloworld {

  def main(args: Array[String]) {
    //定义函数
    def add(a:Int,b:Int):Int = {
     a+b;
    }
    print(add(1,2));
  }
}

2、Scala实现递归

object helloworld {

  def main(args: Array[String]) {
    //递归实现阶乘  ---》递归函数必须显示定义返回值
    def fac(n:Int):Int = if(n==1) 1 else  n * fac(n-1);

    //调用阶乘函数
   print( fac(3));
  }
}

3、函数的默认值和命名参数
传递多个参数

object helloworld {

  def main(args: Array[String]) {

    /*
    给字符串添加前缀和后缀
     */
    def decorate(prefix:String,str:String,suffix:String)={
      prefix + str + suffix;
    }
    //调用decorate函数
    print(decorate("[","hello","]"));
  }
}

3、变长参数

object helloworld {

  def main(args: Array[String]) {

    //变长参数 Int*表示多个参数
    def add(a:Int*) = {
      var sum = 0;
      for (x<-a) sum+=x;//x<-a遍历所有的参数
      sum//返回sum,省略了return sum;
    }
    //调用add方法
      println(add(1,2,3));
  }
}

求1到100的和

object helloworld {

  def main(args: Array[String]) {

    //变长参数 Int*表示多个参数
    def add(a:Int*) = {
      var sum = 0;
      for (x<-a) sum+=x;//x<-a遍历所有的参数
      sum//返回sum,省略了return sum;
    }
    //调用add方法 求和1到100 不能直接用1 to 100
    //1 to 100是一个集合数组对象,这里需要单个参数值
    //通过添加  :_* 将数组转为参数序列
    println(add(1 to 100 :_*));
  }
}

递归实现累加和

object helloworld {

  def main(args: Array[String]) {

   //递归实现累加和
    def sum(args:Int*):Int={
      if (args.length==0) 0 else args.head+sum(args.tail:_*);
    }

    //调用sum()函数
    println(sum(1,2,3));
  }
}

递归实现1-100的和

object helloworld {

  def main(args: Array[String]) {

   //递归实现累加和
    def sum(args:Int*):Int={
      if (args.length==0) 0 else args.head+sum(args.tail:_*);
    }

    //调用sum()函数
    println(sum(1 to 100 :_*));
  }
}
欢迎关注我的公众号:小秋的博客 CSDN博客:https://blog.csdn.net/xiaoqiu_cr github:https://github.com/crr121 联系邮箱:rongchen633@gmail.com 有什么问题可以给我留言噢~
原文地址:https://www.cnblogs.com/flyingcr/p/10327112.html