1

In python can pass a function into a method like so :

def reducer:
   doStuff

run(reducer)

Is there a similar mechanism in Scala ? I could define a trait named reducer and implement a method. Then in run pass the name of the trait and then invoke the method ?

1 Answer 1

5

Yes, there is such thing:

def run(block: Unit => Unit) = {
  println("entering run")
  block()
  println("exiting run")
}

def block() = println("I'm block")

run(block)
// entering run
// I'm block
// exiting run

Note that you may need to change signature of run:

def run(f: Int => Int) {
  println("before call: 1, after call " + f(1))
}

def f(x: Int) = x + 1
run(f)
// before call: 1, after call 2
Sign up to request clarification or add additional context in comments.

1 Comment

And just to add, it's not necessary to create def block() = println("I'm block") if the only thing you're doing is passing it in. It's perfectly valid to say run(_ => println("I'm block")) and cut out the middleman. (I'm sure you know this, but our OP may not)

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.