📜  斯卡拉 |按名称调用的函数

📅  最后修改于: 2022-05-13 01:54:57.849000             🧑  作者: Mango

斯卡拉 |按名称调用的函数

Scala中,当参数通过按值调用函数传递时,它会在调用函数之前计算传入的表达式或参数值一次。但是 Scala 中的按名称调用函数调用表达式并在每次在函数内部访问时重新计算传入表达式的值。这里的示例显示了差异和语法。

按值调用

此方法使用模式内语义。对形式参数所做的更改不会传回给调用者。任何对被调用函数或方法内部形参变量的修改只影响单独的存储位置,不会反映在调用环境中的实参中。此方法也称为按值调用。

句法 :

def callByValue(x: Int)
// Scala program of function call-by-value
  
// Creating object
object GFG 
{
    // Main method
    def main(args: Array[String]) 
    {
        // Defined function
        def ArticleCounts(i: Int) 
        {
            println("Tanya did article " +
                    "on day one is 1 - Total = " + i)
            println("Tanya did article " +
                    "on day two is 1 - Total = " + i)
            println("Tanya did article "+ 
                    "on day three is 1 - Total = " + i)
            println("Tanya did article " +
                    "on day four is 1 - Total = " + i)
        }
  
        var Total = 0;
          
        // function call
        ArticleCounts 
        {
            Total += 1 ; Total
              
        }
    }
}
输出:
Tanya did article on day one is 1 - Total = 1
Tanya did article on day two is 1 - Total = 1
Tanya did article on day three is 1 - Total = 1
Tanya did article on day four is 1 - Total = 1

在这里,通过在上面的程序中使用函数按值调用机制,文章总数没有增加。

点名

按名称调用机制将代码块传递给函数调用,代码块被编译、执行并计算值。消息将首先打印,然后返回值。
句法 :

def callByName(x: => Int)

例子 :

// Scala program of function call-by-name
  
// Creating object
object main 
{
    // Main method
    def main(args: Array[String])
    {
        // Defined function call-by-name
        def ArticleCounts(i: => Int) 
        {
            println("Tanya did articles " + 
                    " on day one is 1 - Total = " + i)
            println("Tanya did articles "+ 
                    "on day two is 1 - Total = " + i)
            println("Tanya did articles " + 
                    "on day three is 1 - Total = " + i)
            println("Tanya did articles " + 
                    "on day four is 1 - Total = " + i)
        }
  
        var Total = 0;
          
        // calling function
        ArticleCounts 
        {
            Total += 1 ; Total
        }
}
}
输出:
Tanya did articles  on day one is 1 - Total = 1
Tanya did articles on day two is 1 - Total = 2
Tanya did articles on day three is 1 - Total = 3
Tanya did articles on day four is 1 - Total = 4

在这里,通过在上面的程序中使用函数名称调用机制,文章的总数将增加。
另一个按名称调用函数的程序。

例子 :

// Scala program of function call-by-name
  
// Creating object
object GFG
{
    // Main method
    def main(args: Array[String])
    {
        def something() = 
        {
            println("calling something")
            1 // return value
        }
          
        // Defined function
        def callByName(x: => Int) = 
        {
            println("x1=" + x)
            println("x2=" + x) 
        }
          
        // Calling function
        callByName(something)
    }
}
输出:
calling something
x1=1
calling something
x2=1