Equivalent of Java 8 Supplier interface in Scala

Viewed 4331

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

A Function0, requiring explicit call:

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

def send(enabled: Boolean, message: () => ProducerRecord): Unit = {
  if (enabled) {
    something.send(message())   
  }
}

Or a by-name parameter:

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

def send(enabled: Boolean, message: => ProducerRecord): Unit = {
  if (enabled) {
    something.send(message)   
  }
}

In latter case message is evaluated every time it is used, if ever, but at the call site it looks just like a normal method call without need to wrap it manually into a function.

Supplier equivalent would be () => ReturnType

def send(enabled: Boolean, message: () => ProducerRecord): Unit {
  if (enabled) {
    something.send(message()))   
  }
}

You can use the lazy argument to delay the parameter evaluation in Scala, like:

  // lazy parameter a
  def foo(a: => Unit) = {
    println("hello")
    a
  }
  // it will delay eval `println("world")`, and it will eval in `foo.a`
  foo(println("world"))
  > hello
  > world
Related