LATER EDIT:
- Related questions:
Why are Scala class methods not first-class citizens?
Motivation for Scala underscore in terms of formal language theory and good style?
Usage of the _
wildcard, or placeholder syntax: Scala placeholder syntax
- In this question I was trying to achieve a more compact syntax, and the solution involved the so-called placeholder syntax. This viewpoint is reinforced in Jason Swartz's Learning Scala, page 74:
Placeholder syntax is especially helpful when working with data structures and collections. Many of the core sorting, filtering, and other data structure methods tend to use first-class functions, and placeholder syntax reduces the amount of extra code required to call these methods.
QUESTION BODY
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!