0

Is there a more idiomatic way to execute a function upon its definition in Scala? Can I do better than the following Function1 definition with its immediate execution?

scala> (new Function1[Int, Int] { def apply(v1: Int) = v1 }) (5)
res0: Int = 5

Are there use cases that justify such calls? I have none, but got curious after I'd been asked about it and thought it might be helpful to find out.

Jacek Laskowski
  • 72,696
  • 27
  • 242
  • 420
  • 1
    `scala> ((x:Int) => x * 2)(3) res0: Int = 6` How does this look? Seriously, why do you want that? :) – S.R.I Oct 26 '13 at 12:36
  • 3
    `{(_: Int) + 1}(5)` `res0: Int = 6`. Just because you can doesn't mean you should. – senia Oct 26 '13 at 12:39

1 Answers1

5

Scala does have a terse syntax for anonymous functions (which you can call immediately):

((x: Int, y: Int) => x + y)(4, 5)

The only use case I am aware of for such instant calls is from another language - JavaScript - where they are heavily used for scoping. But in Scala, you can just define scopes with curly brackets, like:

{
    val a = 5
}
{
    val b = 4
    // a not accessible here
}

so I don't see a use case where such a construct would be useful in Scala.

Leo
  • 37,640
  • 8
  • 75
  • 100
  • Conceivably, you could use it to one-line test your functions in REPL, before you pass them to something else. – mikołak Oct 26 '13 at 15:40
  • @som-snytt read the answer before you rant - I do anwser this question to the best of my knowledge. If you can prove my assumption wrong, write an answer yourself. Otherwise... – Leo Oct 27 '13 at 08:26
  • I've found the pattern useful when refactoring out functions from a block. I can keep the code in place and easily get an overview of which variables are being accessed in the outer scope and that I will need to pass to the new function. – CervEd Apr 19 '20 at 09:16