【发布时间】:2020-10-26 06:27:27
【问题描述】:
在我的项目中,我们正在从 Java 迁移到 Scala。我必须使用 Java 中的一个函数,该函数在 for 循环中使用 continue,并根据 for 循环内的 if 条件返回一个值,如下所示。
private TSourceToken getBeforeToken(TSourceToken token) {
TSourceTokenList tokens = token.container;
int index = token.posinlist;
for ( int i = index - 1; i >= 0; i-- ) {
TSourceToken currentToken = tokens.get( i );
if ( currentToken.toString( ).trim( ).length( ) == 0 ) {
continue;
}
else {
return currentToken;
}
}
return token;
}
为了将其转换为 Scala,我使用了 Yield 选项来过滤掉满足 if 表达式的 else 条件的值,如下所示。
def getBeforeToken(token: TSourceToken): TSourceToken = {
val tokens = token.container
val index = token.posinlist
for { i <- index -1 to 0 by -1
currentToken = tokens.get(i)
if(currentToken.toString.trim.length != 0)
} yield currentToken
}
我无法弄清楚如何返回 for 循环产生的值。错误信息是
type mismatch;
Found : IndexedSeq[TSourceToken]
Required: TSourceToken
我知道yield 收集了 for 循环中的所有值及其内部条件,并导致了一个集合:IndexedSeq & 因此错误消息。我无法想出用 Java 代码编写的逻辑。
谁能告诉我如何在不使用yield 的情况下在Scala 中构建代码并在满足else 条件后打破for循环?
【问题讨论】:
-
哦好吧..现在明白了。它是一个 java Iterator
. -
为什么不把它也转换成 Scala 类型呢?
标签: scala