blue-sky
blue-sky

Reputation: 53896

Passing method as function in Scala - conversion from Python

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 ?

Upvotes: 1

Views: 146

Answers (1)

om-nom-nom
om-nom-nom

Reputation: 62855

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

Upvotes: 5

Related Questions