Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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())   
  }
}
like image 466
Rory Avatar asked Nov 29 '22 13:11

Rory


1 Answers

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)
   }
}
like image 53
Felix Gehring Avatar answered Dec 04 '22 11:12

Felix Gehring