Scala: how to distinguish between an invoked function and a function parameter?

Viewed 64

Suppose I have the following code example in Scala:

def myfunc = {
   println("hello")
   10
}
val myParam = myfunc

When this code runs, myfunc is executed, meaning that the console will print "hello" and myfunc will return the value of 10.

Let's say that I want myParam to hold the function myfunc without invoking it. How can I do it?

2 Answers

Scala differentiates between methods and functions With def you define a method and with val a function. Functions can be assigned to a variable without Parentheses myfunc and are called with Parentheses myfunc()

There is a short conversion syntax to assign a method as a function to a variable

mymethod(_) //use as many underscores as arguments.

However it does not work for zero arguments.

For zero arguments the only option is

def mymethod = {
   println("hello")
   10
}
val myfunc = () => mymethod

See How to use functions as variables (values) in Scala (but please note that the m _-syntax, mentioned in the blog post, will be deprecated in the future).

Given there is a side-effect in myFunc method

def myfunc = {
   println("hello")    <== side-effect here
   10
}

tradition is to anyways hint at that with parenthesis ()

def myfunc() = {
   println("hello")
   10
}

which has the added bonus of being less confusing regarding eta expansion.

Related