Make Java Consumer accept Kotlin lambda

This is likely an odd question, but I’m wondering if anyone has some thoughts on it. I’m working on a DSL that we would like to be compatible with Java, Groovy, and Kotlin. I’m adding Kotlin compatibility to the current codebase, trying to duplicate as little as possible. It’s worked well with the exception of one bit of code written in Groovy, using the Java Consumer functional interface:

PromptOptionals prompts(Consumer<PromptOptionals> definition) {
  DefaultPromptOptionals promptOptionals = new DefaultPromptOptionals()
  definition.accept(promptOptionals)
  prompts = promptOptionals.prompts
  promptOptionals
}

This prompts() method can be called from Java/Groovy fine, but when I call it with Kotlin:

prompts {
  say("test")
  pause(10)
  play("http://someserver.com/file")
}

The 3 method calls say, pause, and play are are add to the list promptOptionals.prompts, and everything goes as expected. But for Kotlin, when definition.accept(promptOptionals) is called, the methods are never added to the list, and the returned promptOptionals variable is just empty. Is there any way that Consumer can be made compatible with Kotlin lambdas?

Answer

of course I’m not confident of your api but for me it looks strange that lambda’s parameter is ignored. It might be you should write:

prompts { prompt ->
  prompt.say("test")
  prompt.pause(10)
  prompt.play("http://someserver.com/file")
}

Leave a Reply

Your email address will not be published. Required fields are marked *