scala教程:函数

介绍

scala是函数式编程语言,与java相比,scala有函数

定义位置

函数要定义在 方法的里面

函数语法

函数的语法,与方法的定义相同

def test():Unit={

}

解释:

  • def:定义函数的关键字

  • Unit:表示无返回值,相当于java中的 void

无参数无返回值

一般是别人封装好的函数,我们直接调用
一般情况,我们很少定义这类函数

object StdFun {

  def main(args: Array[String]): Unit = {
    //定义函数
    def test(): Unit = {
      println("无参无返回值函数")
    }

    test()//调用函数
  }

}

函数声明为 Unit,可以有 return ,但调用返回值是 ()

object StdFun {

  def main(args: Array[String]): Unit = {
    //定义函数
    def test(): Unit = { //Unit,可以有 return ,但调用函数时无返回值
      println("无参无返回值函数")
      return 1
    }

    print(test())
  }

}

执行结果:

无参无返回值函数
()

不能有同名函数

与方法不同,不能有同名函数,也不支持重载

无参数有返回值

一般是别人封装好的函数,我们直接调用
一般情况,我们较少定义这类函数

object StdFun {

  def main(args: Array[String]): Unit = {
    def test(): Int = {
      return 100
    }
    val res=test()
    println(res)
  }

}

有参数无返回值

一般是别人封装好的函数,我们直接调用
一般情况,我们较少定义这类函数

object StdFun {

  def main(args: Array[String]): Unit = {
    def test(s:String): Unit = {
      println("有参无返回值函数,"+s)
    }

    test("测试打印")
  }

}

有参数有返回值

最为常用

object StdFun {

  def main(args: Array[String]): Unit = {
    def add(a:Int,b:Int): Int = {
      println("a="+a)
      println("b="+b)
      return a+b
    }

    val res=add(1,2)
    println("结果:"+res)
  }

}

注意:调用函数时,传参的顺序与参数列表的顺序相同


原文出处:/show_1IX1B8b33fN6.html