There is no difference between a def'ed function and a val'ed function:
scala> def test1 = (str: String) => str + str test1: (String) => java.lang.String scala> val test2 = test1 test2: (String) => java.lang.String = <function1> scala> val test3 = (str: String) => str + str test3: (String) => java.lang.String = <function1> scala> val test4 = test2 test4: (String) => java.lang.String = <function1>
Cm? These are all functions that are denoted by the type X => Y that they have.
scala> def test5(str: String) = str + str test5: (str: String)java.lang.String
Do you see type X => Y ? If so, contact your ophthalmologist because there is none. The type here is (X)Y , commonly used to denote a method.
Actually, test1 , test2 , test3 and test4 are all methods that return functions. test5 is a method that returns a java.lang.String . In addition, test1 test4 not accept parameters through test4 (perhaps only test1 ), while test5 does.
So the difference is pretty simple. In the first case, you tried to assign the val method, but did not fill in the parameters that the method accepts. So this did not succeed until you added a back underscore, which meant turning my method into a function.
In the second example, you had a function, so you didn't have to do anything.
The method is not a function, and vice versa. A function is an object of one of the FunctionN classes. A method is a handle to some piece of code associated with an object.
See various questions about methods versus functions in stack overflows.
Daniel C. Sobral Feb 16 2018-11-11T00: 00Z
source share