Rory Rory - 1 month ago 8
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) {
something.send(message.get())
}
}

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)
   }
}