这是一个Scala类:
class CustomizedStream[K,V](private val queue: BlockingQueue[FetchedDataChunk],
FooTimeoutMs: Int,
private val keyDecoder: Decoder[K],
private val valueDecoder: Decoder[V],
val clientId: String)
extends Iterable[MessageAndMetadata[K,V]] with java.lang.Iterable[MessageAndMetadata[K,V]] {
...
}
和Java代码
Map<String, List<FoStream<byte[], byte[]>>> foStreams = consumer
.createMessageStreams(topicCount);
List<CustomizedStream<byte[], byte[]>> streams = consumerStreams.get(topic);
for (final CustomizedStream stream : streams) {
FoIterator<byte[], byte[]> it = stream.iterator();
while (it.hasNext()) {
System.out.println(it.next().message());
}
}
如何在Scala中重写上述Java代码?我尝试for(stream&lt; - streams)并获取
value foreach is not a member of java.util.List[CustomizedStream(Array[Byte], Array[Byte]]]
Łukasz建议解决方案如下:
for{
stream <- streams.asScala
m <- stream
}{
println(m)
}
我看不到任何输出和
相同for{
stream <- streams.asScala
} {
println(stream) // <- this line shows up
for(m <- stream){
println(m)
}
}
和
相同val foStreams = consumer.createMessageStreams(topicCount);
val streams : java.util.List[KafkaStream[Array[Byte], Array[Byte]]]= foStreams.get(topic);
val itr = streams.iterator()
while(itr.hasNext){
val a = itr.next()
println(a) // <- can see this line
val itr2 = a.iterator()
while(itr2.hasNext()) {
println(itr2.next()) // but not this line
}
}
答案 0 :(得分:0)
您不希望在此处循环播放流,而是在包含java.util.List
的{{1}}上。它包含的内容无关紧要。
显而易见的方法是将java列表转换为scala seq。
CustomizedStream
由于import scala.collection.JavaConverters._
val streams: java.util.List[CustomizedStream[Array[Byte], Array[Byte]]] = ???
for (stream <- streams.asScala) {
// .. code
}
实现了scala CustomizedStream
,您可以将Java代码简化为
Iterable