jonderry
jonderry

Reputation: 23633

Pass a reference to a no-argument method in scala

How can I pass a reference to a no-argument method reference in scala?

For example:

class Foo {
  def foo: String = computeSomethingAndReturnIt
}

object Foo extends App {
  def acceptSupplier(???) { doSomethingWithFooSupplier }
  val f = new Foo
  acceptSupplier(f.foo ???)
}

I know I can define foo to accept Unit by declaring def foo()... and this will work, but is there a way to pass foo and have it accept zero arguments as shown above in the code snippet?

Upvotes: 1

Views: 84

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170745

Or more explicitly:

def acceptSupplier(f: () => String) { ... }
val f = new Foo
acceptSupplier(f.foo _)

Upvotes: 1

Lee
Lee

Reputation: 144136

You can use a by-name argument:

def acceptSupplier(f: => String) { ... }
val f = new Foo
acceptSupplier(f.foo)

Upvotes: 3

Related Questions