2. Scala method and functions

1. The basic function of the form

The basic form of the function defined def 函数名(参数列表):函数结果类型 = {函数体}
functions does not necessarily give the type of results, can be automatically inferred in some cases, but some cases must be displayed, for example, a recursive type of the function gives the results.
If the function only one statement, you can not use curly braces.
Scala method returns the value calculated by the method of the last (expression), the recommended approach is to avoid the use of any style explicit return statement.

2. A special function calls

  • Variable parameter
    Scala allows identification of the last parameter as a function of variable length, may be followed by an asterisk * in the following types of parameters.
    Inside the function, this is a type of variable parameters Array, but if you pass an array as a parameter error, can add a colon and a symbol _ * behind the array, this notation tells the compiler to arr each element as a parameter to a function.
def sum(a: Int*): Int = {
  var s = 0
  for (e <- a) {
    s += e
  }
  s
}
val arr = Array(3, 4, 45)
println(sum(1, 78))
println(sum(arr:_*))
  • The default value of the parameter
    parameter given a default value
def divide(dividend: Int, divisor: Double = 2.0): Double = {
  dividend / divisor
}
println(divide(100))
Released eight original articles · won praise 0 · Views 112

Guess you like

Origin blog.csdn.net/qq_42994084/article/details/102887374