Two ways of defining functions in Scala. What is the difference?

前端 未结 3 1213
自闭症患者
自闭症患者 2020-11-28 03:38

Here is a little Scala session that defines and tries out some functions:

scala> def test1(str: String) = str + str;    
test1: (str: String)java.lang.Str         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 03:45

    The underscore means different things in different contexts. But it can always be thought of as the thing that would go here, but doesn't need to be named.

    When applied in place of parameters, the effect is to lift the method to a function.

    scala> def test1(str: String) = str + str; 
    test1: (str: String)java.lang.String
    
    scala> val f1 = test1 _
    f1: (String) => java.lang.String = 
    

    Note, the method has become a function of type (String) => String.

    The distinction between a method and a function in Scala is that methods are akin to traditional Java methods. You can't pass them around as values. However functions are values in their own right and can be used as input parameters and return values.

    The lifting can go further:

    scala> val f2 = f1 _
    f2: () => (String) => java.lang.String = 
    

    Lifting this function results in another function. This time of type () => (String) => (String)

    From what I can tell, this syntax is equivalent to substituting all of the parameters with an underscore explicitly. For example:

    scala> def add(i: Int, j: Int) = i + j
    add: (i: Int,j: Int)Int
    
    scala> val addF = add(_, _)
    addF: (Int, Int) => Int = 
    
    scala> val addF2 = add _    
    addF2: (Int, Int) => Int = 
    

提交回复
热议问题