Scala函数的参数
Scala中,有两种函数参数的求值策略
Call By Value:对函数实参求值,且仅求一次
Call By Name:函数实参每次在函数体内被用到时都会求值
我们来分析一下,上面两个调用执行的过程:
一份复杂一点的例子:
Scala中的函数参数
默认参数
代名参数
可变参数
(1)默认参数
当你没有给参数赋值的时候,就使用默认值
scala> def fun1(name:String) : String = "Hello " + name
fun1: (name: String)String
scala> fun1("Tom")
res0: String = Hello Tom
scala> fun1()
<console>:13: error: not enough arguments for method fun1: (name: String)String.
Unspecified value parameter name.
fun1()
^
scala> def fun1(name:String="Andy") : String = "Hello " + name
fun1: (name: String)String
scala> fun1("Tom")
res2: String = Hello Tom
scala> fun1()
res3: String = Hello Andy
(2)代名参数
当有多个默认参数的时候,通过代名参数可以确定给哪个参数赋值
scala> def fun2(str:String="Good Morning ",name:String=" Tom ",age:Int=20)=str + name + " and the age of " + name + " is" + age
fun2: (str: String, name: String, age: Int)String
scala> fun2()
res4: String = Good Morning Tom and the age of Tom is20
scala> fun2(name= " Mary ")
res5: String = Good Morning Mary and the age of Mary is20
(3)可变参数
类似于java中的可变参数。即 参数数量不固定。
举例:求多个数字的和:
def sum(x:Int,y:Int) = x+y
def sum(x:Int,y:Int,z:Int) = x+y+z
def sum(args:Int*) = {
var result = 0
for(x <- args) result += x
result
}
scala> def sum(args:Int*) = {
| var result = 0
| for(x <- args) result += x
| result
| }
sum: (args: Int*)Int
scala> sum(1,2,3)
res6: Int = 6
scala> sum(2,3)
res7: Int = 5
scala> sum(2,3,4,5,6,7)
res8: Int = 27
Scala的Lazy值(懒值)
当val被申明为lazy时,它的初始化将被推迟,直到我们首次对它取值。
一个更为复杂一点的例子:读取文件:
铺垫:Spark 核心 RDD (数据集合) 。操作数据集合中的数据时,我们使用算子(函数、方法)。
算子有两种:
1、Transformation : 延时计算,不会立刻触发计算 T
2、Action : 触发计算 A
RDD.T.T.T.T.A
Transformation 用了 lazy值
定义:如果被lazy修饰了,他的初始化会被延迟,推迟到第一次使用该常量、变量的时候。
scala> val x : Int = 10
x: Int = 10
scala> val y : Int = x + 1
y: Int = 11
定义后会立即触发计算
scala> lazy val z : Int = x + 1
z: Int = <lazy>
初始化会被延迟,没有触发计算。当我们第一次使用z的时候,