0

我在 Scala 中查询一个返回 java 可迭代对象的数据库。我调用 spilterator 方法来创建一个 spilterator 对象,但我不知道在 Scala 语法中使用 tryAdvance 或 forEachRemaining。

等效的 Java 语法如下所示,它可以工作:

Spliterator<String> splitStr = nameList.spliterator();
while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));

这是我在 Scala 中的内容:

val nameListSplit = nameList.spliterator()
while (splitStr.tryAdvance((n) -> println("name - " + n))

如您所见,我不知道如何在 scala 中调用 tryAdvance() 方法,forEachRemaining 方法也是如此。

4

1 回答 1

0

直接翻译:

while(res4.tryAdvance { n => System.out.println("name - "+ n) }) ()
//                        ^ = not -                              ^^ unit (or {}); not ;
//                    ^ Braces instead of parens are purely style

地道的翻译:

nameList.forEach { n => println(s"name - $n") }
//       ^ foreach not iterator ^ interpolator not string +
//                      ^ println not System.out.println
//       ^ forEach in Java, foreach in Scala (pretty sure Scala had them first)
for(n <- nameList.asScala) println(s"name - $n")
// ^ for-comprehension (sugar for chained foreach, map, flatMap, filter, withFilter depending on context (generalized monad-comprehensions))
//    ^ <- as in "take n from nameList.asScala"
//                ^ convert to a Scala collection (import collection.JavaConverters._) (needed for foreach not forEach; someone should add AnyVal wrappers for that)
//                        ^ add yield here to do a (flat)map instead of foreach
于 2017-10-11T01:18:27.180 回答