4

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?

Aaron Yodaiken
  • 19,163
  • 32
  • 103
  • 184
  • Just as case to be studied, consider: `val f = (x:Int,y:Int) => x+y`, now try `f _` and `def m = f _`. They all working, and gives `() => (Int, Int) => Int`. – pedrofurla Mar 14 '11 at 23:18
  • possible duplicate of [Difference between method and function in Scala](http://stackoverflow.com/questions/2529184/difference-between-method-and-function-in-scala) – Daniel C. Sobral Mar 15 '11 at 13:51

4 Answers4

9

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

Community
  • 1
  • 1
Esko Luontola
  • 73,184
  • 17
  • 117
  • 128
6
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!

Kris Nuttycombe
  • 4,560
  • 1
  • 26
  • 29
4

is this what you're trying to do?

scala> def g(func: T) = func
g: (func: (String) => String)(String) => String

scala> g(f)("test")
res8: String = test (parsed)
brandon
  • 675
  • 6
  • 10
3

I think you're looking for this: http://jim-mcbeath.blogspot.com/2009/05/scala-functions-vs-methods.html

Antonin Brettsnajdr
  • 4,073
  • 2
  • 20
  • 14