gpt4 book ai didi

java - 在 Scala 中对 Java 列表进行平面映射

转载 作者:行者123 更新时间:2023-11-30 12:03:31 26 4
gpt4 key购买 nike

我有一个 Java 接口(interface),有一个简化的定义

public interface JavaInterface {
List<? extends Foo> getFoos()
}

public interface Foo {
List<? extends Bar> getBars()
}

public interface Bar { }

在 scala 中,我正在尝试 flatMap 列表,并收到关于 scala.collection.mutable.Bufferscala.collection 不匹配的错误。 GenTraversableOnce。看起来 Buffer 确实扩展了 GenTraversableOnce,所以我认为问题与让通用参数对齐有关。

我可以用这段 Scala 代码得到同样的编译错误:

import java.util._
import java.util.{List => JList}
import scala.collection.JavaConverters._

trait Base {
def anotherList: JList[_ <: Base]
}

trait Derived extends Base {}


class Sample
{
def aList: JList[_ <: Base] = new ArrayList[Base]()

val foo = aList.asScala.flatMap(_.anotherList.asScala)
}

失败为

[info] Compiling 1 Scala source to /Users/test/scala/target/scala-2.12/classes ...
[error] /Users/test/scala/src/main/scala/Test.scala:16:25: no type parameters for method flatMap: (f: _$2 => scala.collection.GenTraversableOnce[B])(implicit bf: scala.collection.generic.CanBuildFrom[scala.collection.mutable.Buffer[_$2],B,That])That exist so that it can be applied to arguments (_$2 => scala.collection.mutable.Buffer[_ <: Base])
[error] --- because ---
[error] argument expression's type is not compatible with formal parameter type;
[error] found : _$2 => scala.collection.mutable.Buffer[_ <: Base] where type _$2 <: Base
[error] required: _$2 => scala.collection.GenTraversableOnce[?B] where type _$2 <: Base
[error] val foo = aList.asScala.flatMap(_.anotherList.asScala)
[error] ^
[error] /Users/test/scala/src/main/scala/Test.scala:16:47: type mismatch;
[error] found : _$2 => scala.collection.mutable.Buffer[_ <: Base] where type _$2 <: Base
[error] required: _$2 => scala.collection.GenTraversableOnce[B] where type _$2 <: Base
[error] val foo = aList.asScala.flatMap(_.anotherList.asScala)
[error] ^
[error] /Users/test/scala/src/main/scala/Test.scala:16:32: Cannot construct a collection of type That with elements of type B based on a collection of type scala.collection.mutable.Buffer[_$2].
[error] val foo = aList.asScala.flatMap(_.anotherList.asScala)
[error] ^
[error] three errors found
[error] (Compile / compileIncremental) Compilation failed
[error] Total time: 1 s, completed Aug 28, 2019, 5:11:29 PM

我做错了什么?

最佳答案

我猜这被认为是 Scala 中的错误,而不是您的代码中的错误,因为您的代码在 2.13 中编译得很好。这似乎是 Scala Buffers 与 Java Lists 处理方差的方式不同的结果。我认为修复它的最简单方法是在 flatMap 中使用像 Scala List 这样的协变集合,例如:

aList.asScala.flatMap(_.anotherList.asScala.toList)

您还可以使类型参数不变,例如:

aList.asScala.flatMap(_.anotherList.asScala.asInstanceOf[Buffer[Base]])

aList.asScala.map(_.anotherList.asScala).flatten[Base]

关于java - 在 Scala 中对 Java 列表进行平面映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57700315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com