Function parameter
1. Evaluation of function parameters
(1)Call by value(:)
Evaluate the arguments of the function and only once
(2)Call by name(: =>)
Evaluate the arguments of the function and only once
//Call by value
def sum(x : Int,y : Int) = x + x
sum(3+4,8)
//sum(3+4,8) ---> sum(7,8) --> 14
//Call by name
def sum(x : => Int,y : => Int) = x + x
sum(3+4,8)
//sum(3+4,8) --->(3+4) + (3+4) --> 14
Second, the type of function parameters
(1) Default parameters
When no value is assigned to the parameter, the default value will be used
def func(name : String = "Freedom") : String = "Hello" + name
func() //Hello Freedom
func("Destiny") //Hello Destiny
(2) Nominal parameters
When there are multiple default parameters, you can determine which function parameter to assign the value by using the nominated parameter
def func(str : String = "Hello",name : String = "Freedom") : String = str + name
func() //Hello Freedom
func(name = "Destiny") //Hello Destiny
(3) Variable parameters
Variable parameters similar to java, that is, the number of parameters is not fixed
def sum(num : Int*) = {
var result = 0
for{s <- num}
result += num
result
}
sum(1,2,3,4) //10
abnormal
try{
var word = scala.io.Source.fromFile("C:\\tmp\\log.log").mkString
}catch{
case ex : FileNotFoundException => {
println("File Not Found Exception")
}
case ex : IllegalArgumentException => {
println("Illegal Argument Exception")
}
case _ : Exception => {
println("This is a Exception")
}
}finally{
println("end")
}
def func() = throw new Exception("Exception")
func: ()Nothing
Lazy
If the constant is lazy, its initialization will be delayed until the first time the constant is used
var x : Int = 1
lazy var y : Int = x + 1
y : Int = <lazy>