Converting Java lambda to scala code

How can I convert the following Java Lambda code to Scala:

Java:
DeliverCallback deliverCallback = (consumerTag, delivery) - > {
String message = new String(delivery.getBody(), “UTF-8”);
System.out.println(" [x] Received ‘" + message + "’");
};
channel.basicConsume(queueName, true, deliverCallback, consumerTag - > {});

I use the following Scala code but it error:
val deliverCallback: DeliverCallback = (consumerTag, delivery) => {
var message: String = new String(delivery.getBody, “UTF-8”)
println(" [x] Received ‘" + message + "’")
}
channel.basicConsume(queueName, true, deliverCallback, (consumerTag) => {})

And what does the error say?

2 Likes

There could be many things at play. It seems Scala is not able to handle the type DeliverCallback

From what I can tell, this is RabbitMQ client code; the DeliverCallback class in Java follows the “SAM Pattern” (Single Abstract Method). Scala did not add support for automatic Lambda -> SAM when interfacing with Java code until Scala 2.12 (which is when they started using the native JVM support for lambdas provided in Java 8).

My first guess would be that @soheil08 is not using Scala 2.12. However, without knowing which error they’re seeing, it’s difficult to say for sure. If I have time later, I may try getting a project set up with the RabbitMQ client dependencies and try the original code snippet, but there’s a bunch of setup required to get to the point in the code where they are seeing a problem, and I simply haven’t had the time to look at it yet.