Scala Java 8 Interface Equivalent

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

What does 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
source share
4 answers

This is compiled and executable code. Hope this 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)
   }
}
+6
source

A Function0requiring an explicit call:

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

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

Or a parameter by name:

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

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

In the latter case, the message is evaluated every time it is used, if it is ever, but on the call site it looks like a regular method call, without having to manually transfer it to a function.

+5
source

() => ReturnType

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

You can use lazy argumentto delay grades parameterin Scala , for example:

  // 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
+1
source

Source: https://habr.com/ru/post/1686106/


All Articles