Scala 自动装箱和 Java Map

发布于 2024-10-08 10:37:26 字数 893 浏览 3 评论 0原文

我有一个 Java 方法采用 Map 类型的参数。我正在尝试在 Scala 2.8.1 中为该方法编写一个单元测试,并传入一个文字 Map[Long, Foo]

我的代码如下所示:

import collection.JavaConversions._
x.javaMethod(asJavaMap(Map(1L -> new Foo, 2L -> new Foo)))

编译器给出以下错误:

error: type mismatch;
found   : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]

我也尝试使用

import collection.JavaConverters._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))

and

import collection.JavaConversions._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))

并得到错误:

error: type mismatch;
found   : scala.collection.immutable.Map[scala.Long,Foo]
required: java.util.Map[java.lang.Long,Foo]

我该如何做?

I have a Java method takes an argument of type Map<Long, Foo>. I am trying to write a unit test for that method in Scala 2.8.1 and pass in a literal Map[Long, Foo].

My code looks like this:

import collection.JavaConversions._
x.javaMethod(asJavaMap(Map(1L -> new Foo, 2L -> new Foo)))

The compiler is giving me the following error:

error: type mismatch;
found   : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]

I also tried it with

import collection.JavaConverters._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))

and

import collection.JavaConversions._
x.javaMethod(Map(1L -> new Foo, 2L -> new Foo))

and got the error:

error: type mismatch;
found   : scala.collection.immutable.Map[scala.Long,Foo]
required: java.util.Map[java.lang.Long,Foo]

How do I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

随心而道 2024-10-15 10:37:26

该错误表明具有 scala.Long 键类型的 Scala 映射无法隐式转换为基于 java.lang.Long 的 Java 映射:

found   : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]

作为解决方法,您可以指定所需的手动输入:

x.javaMethod(asJavaMap(Map((1:java.lang.Long) -> new Foo, (2:java.lang.Long) -> new Foo)))

The error says that Scala map with scala.Long key type cannot be implicitly converted to Java map based on java.lang.Long:

found   : scala.collection.immutable.Map[scala.Long,Foo]
required: scala.collection.Map[java.lang.Long,Foo]

As a workaround, you may specify the required type manually:

x.javaMethod(asJavaMap(Map((1:java.lang.Long) -> new Foo, (2:java.lang.Long) -> new Foo)))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文