Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

_ must follow method

Tags:

scala

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?

like image 252
Aaron Yodaiken Avatar asked Nov 30 '22 04:11

Aaron Yodaiken


2 Answers

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

like image 106
Esko Luontola Avatar answered Dec 05 '22 09:12

Esko Luontola


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!

like image 23
Kris Nuttycombe Avatar answered Dec 05 '22 11:12

Kris Nuttycombe