Simplified, from a more complex program:
scala> type T = (String) => String
defined type alias T
scala> def f(s: String) = s + " (parsed)"
f: (s: String)java.lang.String
scala> f _
res0: (String) => java.lang.String = <function1>
scala> def g(func: T) = func _
<console>:6: error: _ must follow method; cannot follow (String) => String
def g(func: T) = func _
^
I don't really understand why this doesn't work. What is the difference between a method and something in the form of (Type1, Type2 ...) => Type
, and what's the right way of getting the function partial from something like that?
In Scala there is a difference between methods and functions. Methods always belong to an object, but functions are objects. A method m
can be converted into a function using m _
See Difference between method and function in Scala
scala> def g(func: String => String) = func(_)
g: (func: (String) => String)(String) => String
Parenthesis make all the difference. This is one of the tricky things about the binding of _; it can be used to lift a method to a closure, and it can be used for partial application, but the two usages are not the same!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With