1

I have the following two methods in Scala:

def myFunc: Int => String = { age =>
  "Here " + age
}

def myFunc2 (age: Int) : String = {
  "Here" + age
}

Is there any difference in these two methods? (other than the names of course). The syntax looks quite different to me. Is it just a matter of style? Is one prefered over the other?

2
  • 1
    You don't have functions here. These are methods. One of them evaluates to a function, and you could convert these to functions, but the code you've posted only defines methods. Commented Jul 10, 2016 at 3:32
  • Ok - good point. I have corrected the terminology. Is there any difference in the two methods though? Commented Jul 10, 2016 at 3:43

1 Answer 1

3

Yes, there is a difference. The former is a method which takes no arguments and returns a function of type Function1[Int, String]. The latter is a method taking a String and returning an Int.

In Scala, methods with arity-0 can be declared and invoked without parenthesis, so invoking myFunction(1) and myFunction2(1) looks the same.

If we'd convert both methods to functions, you'd see the difference in the fact that the former would take the shape of Function0[Function1[Int, String]], while the latter would be Function1[Int, String]:

myFunc: Int => String
myFunc2: (age: Int)String

scala> myFunc _
res6: () => Int => String = <function0>

scala> myFunc2 _
res7: Int => String = <function1>
Sign up to request clarification or add additional context in comments.

2 Comments

I think you might have the terms "former" and "latter" mixed up.
@user2357112 Yup, you're right. Fixed that up, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.