简体   繁体   中英

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?

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM