如何在 Scala 中使用 Java lambda [英] How to use Java lambdas in Scala

查看:17
本文介绍了如何在 Scala 中使用 Java lambda的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

source
    .mapValues(value -> value + " Stream it!!!")
    .print(Printed.toSysOut());

如您所见,mapValues 需要一个 lambda 表达式.

as you can see, mapValues expects a lambda expression.

现在,我使用的是 Java 库,但应用程序是用 Scala 编写的.如何将 Scala lambda 传递给 Java 代码?

Now, I am using Java library but the application is written in Scala. How to pass Scala lambda to Java code?

我尝试了以下方法:

source
  .mapValues(value => value + "hello")
  .print(Printed.toSysOut)

但是编译器抱怨:

[error]   (x$1: org.apache.kafka.streams.kstream.Printed[String,?0(in value x$1)])Unit <and>
[error]   (x$1: org.apache.kafka.streams.kstream.KeyValueMapper[_ >: String, _ >: ?0(in value x$1), String])Unit <and>
[error]   (x$1: String)Unit
[error]  cannot be applied to (org.apache.kafka.streams.kstream.Printed[Nothing,Nothing])
[error]       .print(Printed.toSysOut)
[error]        ^
[error] two errors found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 2 s, completed Nov 19, 2017 7:53:44 PM

推荐答案

错误消息列出了 print 支持的参数类型.其中之一是:

The error message lists the types of arguments that print supports. One of them is:

org.apache.kafka.streams.kstream.Printed[String,?0(in value x$1)]

从错误消息中您可以看到您提供的 Printed.toSysOut 类型为:

From the error message you can see that you're providing Printed.toSysOut with a type of:

org.apache.kafka.streams.kstream.Printed[Nothing,Nothing]

根据Kafka 1 javadoc(Printed 在 Kafka 1.1 中不存在),toSysOut 定义为:

According to the Kafka 1 javadoc (Printed was not present in Kafka 1.1), toSysOut is defined as:

public static <K,V> Printed<K,V> toSysOut()

所以答案问题是 Scala 使用 Nothing 类型推断 KV.您需要明确提供类型.

So the answer problem is that Scala is inferring K and V with types of Nothing. You need to provide the types explicitly.

以下可能会起作用:

source
  .mapValues[String](value -> value + " Stream it!!!")
  .print(Printed.toSysOut[String,String])

这篇关于如何在 Scala 中使用 Java lambda的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆