Scala中的匿名函数详细介绍

2021年3月13日16:47:04 发表评论 584 次浏览

Scala中,

匿名函数

也称为函数文字。不包含名称的函数称为匿名函数。匿名函数提供了轻量级的函数定义。当我们要创建一个内联函数时, 这很有用。

语法如下:

(z:Int, y:Int)=> z*y
Or
(_:Int)*(_Int)
  • 在上面的第一种语法中, =>被称为转换器。转换器用于使用右侧的表达式将符号左侧的参数列表转换为新结果。
  • 在以上第二种语法中, _字符称为通配符, 它​​是表示在匿名函数中仅出现一次的参数的简写方式。

带参数的匿名函数

在对象中实例化函数文字时, 称为函数值。换句话说, 当将匿名函数分配给变量时, 我们可以像调用函数一样调用该变量。我们可以在匿名函数中定义多个参数。

范例1:

// Scala program to illustrate the anonymous method
object Main 
{
     def main(args : Array[String]) 
     {
          
         // Creating anonymous functions
         // with multiple parameters Assign
         // anonymous functions to variables 
         var myfc 1 = (str 1 : String, str 2 : String) => str 1 + str 2
          
         // An anonymous function is created 
         // using _ wildcard instead of 
         // variable name because str1 and
         // str2 variable appear only once 
         var myfc 2 = ( _: String) + ( _: String)
          
         // Here, the variable invoke like a function call
         println(myfc 1 ( "Geeks" , "12Geeks" ))
         println(myfc 2 ( "Geeks" , "forGeeks" ))
     }
}

输出如下:

Geeks12Geeks
lsbin

没有参数的匿名函数

我们可以定义不带参数的匿名函数。在Scala中, 我们可以将匿名函数作为参数传递给另一个函数。

范例2:

// Scala program to illustrate anonymous method
object Main 
{
     def main(args : Array[String]) 
     {
          
         // Creating anonymous functions 
         // without parameter 
         var myfun 1 = () => { "Welcome to lsbin...!!" }
         println(myfun 1 ())
          
         // A function which contain anonymous 
         // function as a parameter
         def myfunction(fun : (String, String) => String) = 
         {
             fun( "Dog" , "Cat" )
         }
          
         // Explicit type declaration of anonymous
         // function in another function
         val f 1 = myfunction((str 1 : String, str 2 : String) => str 1 + str 2 )
          
         // Shorthand declaration using wildcard
         val f 2 = myfunction( _ + _ )
         println(f 1 )
         println(f 2 )
     }
}

输出如下:

Welcome to lsbin...!!
DogCat
DogCat

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: