Aaron Watters
Aaron Watters

Reputation: 2846

refer to scala function by name?

Here is another stupid scala question regarding functions as first class objects in Scala. I'm very sorry if this is a repeat, as it probably is.

In Python, Lisp, Perl, Scheme, etcetera I'm used to creating function values and assigning them names and passing them around to other functions, like this in python:

>>> def yyy(c):
...     return c.upper()
... 
>>> yyy
<function yyy at 0x1032965f0>
>>> yyy('a')
'A'
>>> def compose(f,g):
...     def composition(x):
...         return f(g(x))
...     return composition
... 
>>> compose(ord, yyy)('a')
65

In scala I don't know how to do this because scala always wants to evaluate the function as far as I can tell. How do you refer to an unevaluated function in scala and pass it around, save it in data structures, etcetera?

For example, I can't do it this way, apparently:

scala> def yyy(c: Char) = {
     |     c.toUpper
     | }
    yyy: (c: Char)Char

scala> yyy('a')
res5: Char = A

scala> yyy
<console>:9: error: missing arguments for method yyy;
follow this method with `_' if you want to treat it as a partially
applied function
          yyy
          ^

scala> yyy_
<console>:8: error: not found: value yyy_
          yyy_
          ^

As you can see, I tried and failed to make sense of the "_" hint. Any clues? How do you refer to a function without evaluating it?

Upvotes: 1

Views: 105

Answers (1)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369438

yyy is not a function, it's a method. You have to either convert it to a function using η-expansion

yyy _

or use a function in the first place

val yyy = (c: Char) => c.toUpper
// or
val yyy: Char => Char = c => c.toUpper
// or
val yyy: Char => Char = _.toUpper

Upvotes: 4

Related Questions