如何在Scala中使用Java Lambda

编程入门 行业动态 更新时间:2024-10-10 11:21:54
本文介绍了如何在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 (在Kafka 1.1中不存在Printed),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的K和V.您需要明确提供类型.

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

以下内容可能会起作用:

The following will probably work:

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

更多推荐

如何在Scala中使用Java Lambda

本文发布于:2023-11-28 04:47:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641008.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   Scala   Lambda   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!