在Java中调用Scala中的函数

时间:2017-11-27 11:20:42

标签: java scala

我在Scala中有以下功能:

   select * from table1 where  col1  in (select col2 from table2 ) ;

然后尝试用Java调用:

object Path {

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

编译器抱怨:

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

我做错了什么?

1 个答案:

答案 0 :(得分:2)

由于示例中的processString => String类型的函数,要调用函数,您需要在其上调用apply()

当客户端代码使用parenthsis apply时,默认情况下Scala会调用(),但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

注意:扩展版的scala函数是

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

从java调用

public class Test {

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