函数入门
函数的定义与调用,在Scala中定义函数时,需要定义函数的函数名、参数、函数体。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sayHello(name:String, age:Int) = {
4 if(age >= 18) {
5 printf("Hi, %s, you are a big boy!\n", name)
6 age
7 } else {
8 printf("Hi, %s, you are a children!\n", name)
9 age
10 }
11}
12// Exiting paste mode, now interpreting.
13sayHello: (name: String, age: Int)Int
14scala> sayHello("padluo", 30)
15Hi, padluo, you are a big boy!
16res1: Int = 30
Scala要求必须给出所有参数的类型,但是不一定给出函数返回值的类型,只要右侧的函数体不包含递归的语句,Scala就可以自己根据右侧的表达式推断出返回类型。
在代码块中定义包含多行语句的函数体,
单行的函数,
1scala> def sayHello(name:String) = printf("Hello, " + name)
2sayHello: (name: String)Unit
3scala> sayHello("padluo")
4Hello, padluo
如果函数体中有多行代码,则可以用代码块的方式包裹多行代码,代码块中最后一行的返回值就是整个函数的返回值,与Java中不同,不是使用return返回值的。
1# 函数定义没有写=
2scala> :paste
3// Entering paste mode (ctrl-D to finish)
4def sum(n:Int) {
5 var result = 0
6 for(i <- 1 to n) {
7 result += i
8 }
9}
10// Exiting paste mode, now interpreting.
11sum: (n: Int)Unit
12# 函数定义写了=,但是最后一行是赋值语句
13scala> :paste
14// Entering paste mode (ctrl-D to finish)
15def sum(n:Int) = {
16 var result = 0
17 for(i <- 1 to n) {
18 result += i
19 }
20}
21// Exiting paste mode, now interpreting.
22sum: (n: Int)Unit
23# 正确定义
24scala> :paste
25// Entering paste mode (ctrl-D to finish)
26def sum(n:Int) = {
27 var result = 0
28 for(i <- 1 to n) {
29 result += i
30 }
31 result
32}
33// Exiting paste mode, now interpreting.
34sum: (n: Int)Int
递归函数与返回类型,如果在函数体内递归调用函数自身,则必须手动给出函数的返回类型。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def fab(n:Int):Int = {
4 if(n<=0) 1
5 else fab(n-1) + fab(n-2)
6}
7// Exiting paste mode, now interpreting.
8fab: (n: Int)Int
9scala> fab(10)
10res5: Int = 144
默认参数和带名参数
默认参数,在Scala中,有时我们调用某些函数时,不希望给出具体的参数值,而希望使用参数自身默认的值,此时就在定义函数时使用默认参数。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sayHello(name:String, age:Int=20) {
4 print("Hello, " + name + ", your age is " + age)
5}
6// Exiting paste mode, now interpreting.
7sayHello: (name: String, age: Int)Unit
8scala> sayHello("leo")
9Hello, leo, your age is 20
10scala> sayHello("leo", 30)
11Hello, leo, your age is 30
如果给出的参数不够,则会从左到右依次应用参数。
带名参数,在调用函数时,也可以不按照函数定义的参数顺序来传递参数,而是使用带名参数的方式来传递。
1scala> sayHello(age=30, name="leo")
2Hello, leo, your age is 30
还可以混合使用未命名参数和带名参数,但是未命名参数必须排在带名参数前面。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sayHello(firstName:String, middleName:String="Willian",lastName:String="Croft") = print(firstName + " " + middleName + " " + lastName)
4// Exiting paste mode, now interpreting.
5sayHello: (firstName: String, middleName: String, lastName: String)Unit
6scala> sayHello("leo")
7leo Willian Croft
8scala> sayHello("leo", lastName="Jack", middleName="Tom")
9leo Tom Jack
变长参数
如果函数体包含在花括号中,但没有前面的=号,那么返回类型就是Unit,这样的函数被称为过程,过程不返回值,我们调用它仅仅是为了它的副作用,有人不喜欢这种简明写法定义过程,并建议大家总是显式声明Unit返回类型。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sum(nums:Int*) {
4 var result = 0
5 for(num <- nums) {
6 result += num
7 }
8 result
9}
10// Exiting paste mode, now interpreting.
11sum: (nums: Int*)Unit
12scala> sum(1,2,3,4,5)
13scala>
在Scala中,有时我们需要将函数定义为参数个数可变的形式,则此时可以使用变长参数定义函数。
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sum(nums:Int*) = {
4 var result = 0
5 for(num <- nums) {
6 result += num
7 }
8 result
9}
10// Exiting paste mode, now interpreting.
11sum: (nums: Int*)Int
12scala> sum(1,2,3,4,5)
13res0: Int = 15
使用序列调用变长参数,如果想要将一个已有的序列直接调用变长参数函数,是不对的,如val s = sum(1 to 5)
。此时需要使用Scala特殊的语法将参数定义为序列sum(1 to 5: _*)
,让Scala解释器能够识别。
1scala> 1 to 5
2res6: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
3scala> sum(1 to 5)
4<console>:13: error: type mismatch;
5 found : scala.collection.immutable.Range.Inclusive
6 required: Int
7 sum(1 to 5)
8scala> sum(1 to 5:_*)
9res3: Int = 15
10scala> sum(1 to 5: _*)
11res4: Int = 15
12scala> sum(1 to 5 : _*)
13res5: Int = 15
使用递归函数实现累加,
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3def sum2(nums:Int*): Int = {
4 if (nums.length == 0) 0
5 else nums.head + sum2(nums.tail: _*)
6}
7// Exiting paste mode, now interpreting.
8sum2: (nums: Int*)Int
9scala> sum(1,2,3,4,5)
10res8: Int = 15
过程、lazy值和异常
过程,在Scala中,定义函数时,如果函数体直接包裹在了花括号里面,而没有使用=连接,则函数的返回值类型就是Unit。这样的函数称为过程。过程通常用于不需要返回值的函数。
过程还有一种写法,就是将函数的返回值类型定义为Unit。
1# 函数,没有显式声明返回值类型,自动推断返回值类型
2scala> def sayHello(name:String) = "Hello, " + name
3sayHello: (name: String)String
4scala> sayHello("padluo")
5res1: String = Hello, padluo
6# 过程,没有使用=连接,调用它仅仅是为了它的副作用(print ...),即使块最后的表达式有值,整个函数最终是没有值返回的
7scala> def sayHello(name:String) {print("Hello, " + name); "Hello, " + name}
8sayHello: (name: String)Unit
9scala> sayHello("padluo")
10Hello, padluo
11# 显式声明返回值类型为Unit,即使块最后的表达式有值,函数最终也是没有值返回
12scala> def sayHello(name:String): Unit = "Hello," + name
13sayHello: (name: String)Unit
14scala> sayHello("padluo")
15scala>
lazy值,如果将一个变量声明为lazy,则只有在第一次使用该变量时,变量对应的表达式才会发生计算,这种特性对于特别耗时的操作特别有用,比如打开文件进行IO,进行网络IO等。
1scala> import scala.io.Source._
2import scala.io.Source._
3scala> lazy val lines = fromFile("/home/hadoop/test.txt").mkString
4lines: String = <lazy>
5scala> print(lines)
6Hello World
7scala> lazy val lines = fromFile("/home/hadoop/test1.txt").mkString
8lines: String = <lazy>
9scala> print(lines)
10java.io.FileNotFoundException: /home/hadoop/test1.txt (No such file or directory)
11 at java.io.FileInputStream.open(Native Method)
12 at java.io.FileInputStream.<init>(FileInputStream.java:146)
13 at scala.io.Source$.fromFile(Source.scala:91)
14 at scala.io.Source$.fromFile(Source.scala:76)
15 at scala.io.Source$.fromFile(Source.scala:54)
16 at .lines$lzycompute(<console>:14)
17 at .lines(<console>:14)
18 ... 32 elided
19scala> val lines = fromFile("/home/hadoop/test1.txt").mkString
20java.io.FileNotFoundException: /home/hadoop/test1.txt (No such file or directory)
21 at java.io.FileInputStream.open(Native Method)
22 at java.io.FileInputStream.<init>(FileInputStream.java:146)
23 at scala.io.Source$.fromFile(Source.scala:91)
24 at scala.io.Source$.fromFile(Source.scala:76)
25 at scala.io.Source$.fromFile(Source.scala:54)
26 ... 32 elided
27scala> def getLines = fromFile("/home/hadoop/test1.txt").mkString
28getLines: String
29scala> getLines
30java.io.FileNotFoundException: /home/hadoop/test1.txt (No such file or directory)
31 at java.io.FileInputStream.open(Native Method)
32 at java.io.FileInputStream.<init>(FileInputStream.java:146)
33 at scala.io.Source$.fromFile(Source.scala:91)
34 at scala.io.Source$.fromFile(Source.scala:76)
35 at scala.io.Source$.fromFile(Source.scala:54)
36 at .getLines(<console>:14)
37 ... 32 elided
val lines = fromFile("/home/hadoop/test1.txt").mkString
,即使文件不存在也不会报错,只有第一个使用变量时会报错,证明了表达式计算的lazy特性。
异常,
1scala> :paste
2// Entering paste mode (ctrl-D to finish)
3try {
4 throw new IllegalArgumentException("illegal argument!")
5} catch {
6 case _: IllegalArgumentException => print("sorry, error!")
7} finally {
8 print("\nrelease io resources!")
9}
10// Exiting paste mode, now interpreting.
11sorry, error!
12release io resources!
1scala> import java.io._
2import java.io._
3scala> :paste
4// Entering paste mode (ctrl-D to finish)
5try {
6 throw new IOException("user defined exception")
7} catch {
8 case e1: IllegalArgumentException => println("illegal argument")
9 case e2: IOException => print("io exception")
10}
11// Exiting paste mode, now interpreting.
12io exception
本文首发于steem,感谢阅读,转载请注明。
微信公众号「数据分析」,分享数据科学家的自我修养,既然遇见,不如一起成长。
读者交流电报群
知识星球交流群
来源:CSDN
作者:padluo
链接:https://blog.csdn.net/padluo/article/details/79679020