fr_andres fr_andres - 2 months ago 9
Scala Question

Scala error: value <FUNCTION_NAME> is not a member of object <OBJECT_NAME>

LATER EDIT:

other related question: Why are Scala class methods not first-class citizens?




I'm trying out Scala's support for first-order functions, and encountered this problem, about passing methods as parameters. As far as I understood, the solution is to wrap the method with a (named or anonymous) first-order function. This worked for me:

def wrapperFn(s:String):String = s.reverse


wrapperFn
can be now passed as parameter to other higher-order functions, or as value to other definitions like this one:

val otherGoodFn:(String=>String) = goodWrapperFn


So far so good. The problem came when I tried to mix both steps (avoiding the somewhat verbose use of the
s
parameter), and directly pass the method to a function-typed value, like this:

def errorFn:(String=>String) = String.reverse


Which throws the following error:

error: value reverse is not a member of object String
def errorFn:(String=>String) = String.reverse
^


Which I don't understand, because this works as expected:

val s:String = "hello"
s.reverse


So apparently the method is a member of the instance, but not of the Object/Class(??) It seems that Scala handles the class and object lifetime in a very different way as Java does. So my question, now more concisely:


  • Is the error caused by some stupid mistake or is it indeed not allowed? And if not allowed, why?



Thanks in advance!

Answer

String.reverse would be calling a static method (or a method on an object instead of a class in Scala terms).

You can do

def errorWrapperFn:(String=>String) = _.reverse

The underscore here allows you to access the method/function parameters without having to give them a name.