Rory Rory - 5 months ago 47
Scala Question

Equivalent of Java 8 Supplier interface in Scala

The following Java 8 code passes a lambda to a function that defers execution of the generateMessage(...) function only if logging is enabled.

What would the equivalent Scala code look like?

producer.send(true, () -> generateMessage(1, "A Test Message"));

public void send(boolean enabled, Supplier<ProducerRecord> message) {
if (enabled) {

Answer Source

This is compilable and runnable code. Hope it helps.

object HelloWorld {
   def main(args: Array[String]) = {

        send(true, () => "Foo")

        def send(enabled: Boolean, supplier: () => String) =
            if (enabled) somethingSend(supplier())

        def somethingSend(message: String) = println(message)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download