softshipper
softshipper

Reputation: 34099

Call function from Scala in Java

I have the following function in Scala:

object Path {

  def process: String => String =
    ???
}

and then trying to call in Java as:

KStream<String, String> source = builder
    .stream("PATHS-UPSERT-PRODUCER", Consumed.with(Serdes.String(), Serdes.String()))
    .mapValues(value -> Path.process(value));

The compiler complains:

[error]   required: no arguments
[error]   found: java.lang.String
[error]   reason: actual and formal argument lists differ in length
[error]         .mapValues(value -> Path.process(value));

What am I doing wrong?

Upvotes: 0

Views: 647

Answers (1)

prayagupadhyay
prayagupadhyay

Reputation: 31252

Since process in your example is a function of type String => String, To invoke a function, you need to call apply() on it.

Scala by default invokes apply when client code uses parenthsis (), but java won't recognise that.

object Path {
    def process: String => String = (input: String) => "processed"
}

scala> process("some value")
res88: String = processed

scala> process.apply("some value")
res89: String = processed

NOTE: The expanded version of scala function is,

  def process = new Function[String, String] {
    override def apply(input: String) = "processed"
  }

invoking from java,

public class Test {

    public static void main(String[] args) {
        Path f = new Path();
        System.out.println(f.process().apply("som input")); //prints processed
    }
}

Upvotes: 2

Related Questions