1、函数定义
/** * 函数返回Unit */ def fun() = { println("this is a function") } /** * 函数有返回值 * @return */ def fun1():Int = {1} /** * 多参数函数 * @param x 默认0 * @param y 默认0 * @return */ def fun2(x:Int = 0, y:Int = 0) = {if(x > y) x else y} /** * 递归函数 阶乘 必须要指定返回值 * @param x * @return */ def fun3(x:Int):Long = { if(x < 1) 1 else x * fun3(x - 1) }
2、函数调用
fun() println(fun1()) println("多参数函数="+fun2(2,5)) println("使用默认值的多参数函数="+fun2(1)) //默认使用第2个参数的默认值 println("使用带参数名称的多参数函数="+fun2(y = 2, x = 4))//指明了参数名称就不需要按照顺序向函数传递参数 println("递归函数解决阶乘5="+fun3(5))
3、匿名函数
//fun: (Int, Int) => Unit = $$Lambda$1098/1665837086@5be51aa val afun = (x:Int,y:Int)=>{println(s"param1=${x} param2=${y}")} //param1=2 param2=3 afun(2,3) //无参数匿名函数 val afun1 = ()=> { System.getProperty("user.dir") } afun1()
4、内嵌函数
/** * 内嵌函数 * @param x */ def fun5(x:Int): Unit ={ def fun6(s:Int) = println(s"${s}偶数") def fun7(s:Int) = println(s"${s}奇数") if(x % 2 == 0) fun6(x) else fun7(x) } fun5(34) 输出: 34偶数
5、偏函数
/** * 测试偏函数 * @param date * @param message */ def log(date:Date, message:String) = { println(date + "----" + message) } 调用: /** * log() 方法接收两个参数:date 和 message。我们在程序执行时调用了三次, * 参数 date 值都相同,message 不同。我们可以使用偏应用函数优化以上方法, * 绑定第一个 date 参数,第二个参数使用下划线(_)替换缺失的参数列表,并把这个新的函数值的索引的赋给变量 */ val date = new Date /** * logPar: String => Unit = $$Lambda$1201/1696998152@792e8181 * */ val logPar = log(date, _:String) logPar("消息1") logPar("消息2") logPar("消息3") //f: (java.util.Date, String) => Unit = $$Lambda$1205/750996693@684b26b7 val f = log _ println(f(date, "消息4"))
6、函数调用的lazy
/** * lazy 只有在使用的时候才会加载 本身这个文件是不存在的 * 如果不加lazy修饰 会报错 java.io.FileNotFoundException: D:\aa.txt (系统找不到指定的文件。) * 加了lazy修饰返回的值 file: scala.io.BufferedSource = <lazy> */ lazy val file = Source.fromFile("D:\\aa.txt") for(content <- file.getLines()) println(content)
7、函数的变长参数
/** * 变长参数 * @param num * @return */ def fun8(num:Int*):Int = { if(num.length == 0) 0 else num.head + fun8(num.tail :_*) } 调用: //函数的变长参数 println("1-10累加="+fun8(1,2,3,4,5,6,7,8,9,10)) /** * 上面的调用很不方便,使用下面的方式就很好 * :_*标注告诉编译器把Range的每个元素当作参数,而不是当作单一的参数传给函数 */ println("1-10累加="+fun8(1 to 10 :_*)) 输出: 1-10累加=55 1-10累加=55