当前位置:网站首页>Scala method and function notes

Scala method and function notes

2022-06-13 03:28:00 TRX1024

Scala There are methods and functions , The semantic difference between them is very small .Scala Method is part of the class , and Function is an object , It can be assigned to a variable . In other words, a function defined in a class is a method .Scala The function in is a complete object ,Scala The functions in are actually inherited Trait Object of class .

Scala Use in val Statements can define functions ,def Statement definition method .

Be careful : Some translation functions (function) With the method (method) There is no difference .

1、Scala Method / Function definition

object Test {

  def main(args: Array[String]): Unit = {
    fun(10, 20)
    println(sum(10, 20))
    println(sum2(30, 20))
  }

  def fun(a: Int, b: Int) = {
    println("a=" + a)
    println("b=" + b)
  }

  def sum(a: Int, b: Int) = a + b

  def sum2(a: Int, b: Int): Int ={
    return a + b
  } 

}
  • Method is defined by a def Keyword start , This is followed by a list of optional parameters , A colon : And the return type of the method , An equal sign = , Finally, the main body of the method .

  • If the method does not return a value , The return type is Unit, Be similar to Java Medium void. Methods can write return value types , Or not , Automatically infer . Sometimes it cannot be omitted , For example Recursive function in 、 The return type of the function is Function type when , Write in method return Isochronous .

  • Scala When there is a return value in , Can write return, Or not , The function returns the last line as a result .

  • The method body can be timed in one line , Don't write { } .

  • Scala Specifies that the parameters passed to the method are Constant val Of , No var Of .

2、Scala Function name call (call-by-name)

Scala The interpreter parses function parameters (function arguments) There are two ways :

  • Value transfer call (call-by-value): First calculate the value of the parameter expression , And then apply it to the inside of the function ;
  • Call by name (call-by-name): Apply the non evaluated parameter expression directly inside the function
object SayHello {

  def main(args: Array[String]): Unit = {
    println(" Value transfer call :")
    delayed0(time())
    println("===================")

    println(" Call by name :")
    delayed(time())
    println("===================")
  }

  def time() = {
    println(" Acquisition time , It's in nanoseconds ")

    System.nanoTime
  }

  def delayed0(t : Long)={
    println(" stay  delayed0  In the way ")
    println(" Parameters "+t)
    t
  }

  def delayed(t: => Long) = {
    println(" stay  delayed  In the way ")
    println(" Parameters : " + t)
    t
  }
}

We declared that delayed Method , This method is used in variable names and variable types => Symbol to set the name call ; Output results :

 Value transfer call :
 Acquisition time , It's in nanoseconds 
 stay  delayed0  In the way 
 Parameters 232873973675933
===================
 Call by name :
 stay  delayed  In the way 
 Acquisition time , It's in nanoseconds 
 Parameters : 232873984381351
 Acquisition time , It's in nanoseconds 
===================

in short , The value passing call will calculate the value of the parameter before calling the method , The named call is after the method call , Call... Where parameters are used inside a method .

3、Scala Closure

Closure is a function , The return value depends on one or more variables declared outside the function .

Generally speaking, a closure can be simply regarded as another function that can access local variables in a function .

We introduce a free variable factor, This variable is defined outside the function .

Function variables defined in this way multiplier Become a " Closure ", Because it refers to variables defined outside the function , The process of defining this function is to capture this free variable to form a closed function .

example :

object Test {  
   def main(args: Array[String]) {  
      var factor = 3  
      val multiplier = (i:Int) => i * factor  
      println( "muliplier(1) value = " +  multiplier(1) )  
      println( "muliplier(2) value = " +  multiplier(2) )  
   }  
  
}  

Properties of closures

  • 1. Function nested function
  • 2. Functions can reference external parameters and variables internally
  • 3. Parameters and variables are not recycled by the garbage collection mechanism

Common ways to create closures The function is created in the function

  • 1. How to set private variables
  • 2. Unsuitable scene : Functions that return closures are very large functions
  • 3. Disadvantages resident memory , Will increase memory usage , Improper use causes memory leakage

Why use closures

  • 1. To get local variables inside a function
  • 2. A local variable inside a function that can only be read by a child function inside the function
  • 3. Closures are bridges between the internal and external links of functions

Use of closures

  • You can read the internal variables of the function , You can always keep the value of a variable in memory

4、 Recursive function

Must develop a The return type of the function


def fun(num :Int) :Int= {
   if(num ==1)
      num
   else 
      num * fun2(num-1)
}
print(fun(4))

5、Scala function - Default parameter value

object Test {
   def main(args: Array[String]) {
        println( " Return value  : " + addInt() );
   }
   def addInt( a:Int=5, b:Int=7 ) : Int = {
      var sum:Int = 0
      sum = a + b

      return sum
   }
}

6、Scala function - Variable parameters

Scala Set the variable parameter by placing an asterisk after the type of parameter ( Repeatable parameters ).

object Test {
   def main(args: Array[String]) {
        printStrings("I", "Love", "Scala");
   }
   def printStrings( args:String* ) = {
      var i : Int = 0;
      for( arg <- args ){
         println("Arg value[" + i + "] = " + arg );
         i = i + 1;
      }
   }
}

7、Scala function - Anonymous functions

Scala The syntax for defining anonymous functions in is simple , To the left of the arrow is a list of parameters , On the right is the function body .

def main(args: Array[String]): Unit = {
    value1()
    value2(2)
    println(value3(3,4))
    println(value4(4,5))
  }

  //  Nonparametric anonymous function 
  val value1 = () => {
    println("Hello word")
  }

  //  Anonymous functions with parameters 
  val value2 = (a: Int) => {
    println(a)
  }

  //  Multiple parameters   There is a return 
  val value3 = (a: Int, b: Int) => {
    a * b
  }

  val value4 = (a: Int, b: Int) => a * b

8、Scala Higher order function

Higher order function (Higher-Order Function) Is a function that operates on other functions .

Scala Higher order functions are allowed in , Higher order functions can use other functions as parameters , Or use functions as output .

In the following example ,apply() Function uses another function f and value v As a parameter , The function f The parameter... Is called again v:

object Test {
   def main(args: Array[String]) {

      println( apply( layout, 10) )

   }
   //  function  f  and   value  v  As a parameter , The function  f  The parameter... Is called again  v
   def apply(f: Int => String, v: Int) = f(v)

   def layout[A](x: A) = "[" + x.toString() + "]"
   
}

apply() in f Use =>String, Indicates that a function is called by name , The passed in function will be called at the position used by the function body .

原网站

版权声明
本文为[TRX1024]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280529584432.html

随机推荐