Difference between method and function in Scala

后端 未结 9 2029
温柔的废话
温柔的废话 2020-11-21 07:22

I read Scala Functions (part of Another tour of Scala). In that post he stated:

Methods and functions are not the same thing

9条回答
  •  清酒与你
    2020-11-21 08:02

    Here is a great post by Rob Norris which explains the difference, here is a TL;DR

    Methods in Scala are not values, but functions are. You can construct a function that delegates to a method via η-expansion (triggered by the trailing underscore thingy).

    with the following definition:

    a method is something defined with def and a value is something you can assign to a val

    In a nutshell (extract from the blog):

    When we define a method we see that we cannot assign it to a val.

    scala> def add1(n: Int): Int = n + 1
    add1: (n: Int)Int
    
    scala> val f = add1
    :8: error: missing arguments for method add1;
    follow this method with `_' if you want to treat it as a partially applied function
           val f = add1
    

    Note also the type of add1, which doesn’t look normal; you can’t declare a variable of type (n: Int)Int. Methods are not values.

    However, by adding the η-expansion postfix operator (η is pronounced “eta”), we can turn the method into a function value. Note the type of f.

    scala> val f = add1 _
    f: Int => Int = 
    
    scala> f(3)
    res0: Int = 4
    

    The effect of _ is to perform the equivalent of the following: we construct a Function1 instance that delegates to our method.

    scala> val g = new Function1[Int, Int] { def apply(n: Int): Int = add1(n) }
    g: Int => Int = 
    
    scala> g(3)
    res18: Int = 4
    

提交回复
热议问题