Reputation: 23633
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
Reputation: 170745
Or more explicitly:
def acceptSupplier(f: () => String) { ... }
val f = new Foo
acceptSupplier(f.foo _)
Upvotes: 1
Reputation: 144136
You can use a by-name argument:
def acceptSupplier(f: => String) { ... }
val f = new Foo
acceptSupplier(f.foo)
Upvotes: 3