简体   繁体   English

用Java从Scala调用函数

[英]Call function from Scala in Java

I have the following function in Scala: 我在Scala中具有以下功能:

object Path {

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

and then trying to call in Java as: 然后尝试以以下方式在Java中调用:

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. 由于示例中的processString => String类型的函数, 要调用一个函数,您需要在其上调用apply()

Scala by default invokes apply when client code uses parenthsis () , but java won't recognise that. 默认情况下,当客户端代码使用括号() ,Scala会调用apply ,但是java不会识别它。

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, 注意:scala函数的扩展版本是,

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

invoking from java, 从Java调用

public class Test {

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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