Explanation of the principle of method to function in Scala

  In Scala, there is such a grammar called method-to-function, but it is not. The essence of this is that the function calls this method. The function is still the function, and the method is still the method. The following explains through the code.

  1. First write down the most commonly used methods for explanation
object CallByName {
    
    
  def main(args: Array[String]): Unit = {
    
    
    val func = m _
    func(5)
  }
  // 定义如下方法
  def m(x:Int):Unit = println(x * x)
}

The execution result is as follows: It
Insert picture description here
  can be seen that when the method func is executed, the result obtained is the result calculated by the logic of the method m. This way of writing seems to convert the method m into the function func, but it is not.
  You can easily see the reason by executing it through the scala shell. First, define a method m, as shown below,
Insert picture description here
and then execute'm _'separately. As shown in the figure, we
Insert picture description here
can see that when we execute'm _', it is actually generated A function has not changed, and the logic of'x * x'does not appear in this function. The m method is actually called inside this function, but the signature of this method is the same as that of the m method. IDEA is also very easy to see through the Debug out, I played here two breakpoints, as shown
Insert picture description here
by Debug run, run to the function func when, as shown below
Insert picture description here
and then continue to the next step, as shown below
Insert picture description here
can to , The m method itself is actually executed.
  Through the following code, you can have a clearer understanding of "method to function"

object CallByName {
    
    
  def main(args: Array[String]): Unit = {
    
    

    val func = m _
    /*等价于*/
    val func2 = (y:Int) => m(y)
    /*等价于*/
    val func3 = (v:Int) => {
    
    
      m(v)
    }
    func(5)
  }
  // 定义如下方法
  def m(x:Int):Unit = println(x * x)
}

Many books may explain this phenomenon as a method to a function, but strictly speaking, only a new function is generated, and this method is called inside the function. I write this in the hope that everyone has a clearer understanding of this .

Guess you like

Origin blog.csdn.net/AnameJL/article/details/114767927