Scala Basics function

Definition and calling functions

In Scala when the defined function, you need to define the function name, parameters, functions Functions.

Our first function is as follows:

  

  def sayHello(name: String, age: Int) = {

 

      if (age > 18) { printf("hi %s, you are a big boy\n", name); age }

 

      else { printf("hi %s, you are a little boy\n", name); age

 

  }

 

    sayHello("leo", 30)

 

 

Scala requirements must be given to all types of parameters, but not necessarily given type of return value of the function, as long as the right side of the body of the function is not included in the statement recursion, Scala can infer the return type according to their expression on the right.

 

 

  Defined function comprises a plurality of rows of the statements in the code block

One-way function: DEF the sayHello (name: String) = Print ( "the Hello," + name)

If multiple lines of code in the body of the function, can use the code block wrapping lines of code, the code block is the last line of the return value of the function return value of the whole. And Java different, instead of using return return value.

 

Functions such as, for accumulator functions:

def sum(n: Int) = {

  was some = 0;

  for(i <- 1 to n) sum += i

  sum

}

 

Recursive function returns the type

If the recursive function is a function of the body itself, you must manually return type of the function is given.

 

For example, to achieve the classic Fibonacci number:

9 + 8; 8 + 7 + 7 + 6; 7 + 6 + 6 + 5 + 6 + 5 + 5 + 4; ....

 

def fab(n: Int): Int = {

  if(n <= 1) 1

  else fab(n - 1) + fab(n - 2)

}

 

Guess you like

Origin www.cnblogs.com/YuanWeiBlogger/p/11415477.html