如何从scala中的for循环返回产生的值?

Met*_*ata 0 scala

在我的项目中,我们正在从 Java 迁移到 Scala。我必须使用 Java 中的一个函数,该函数在continuefor 循环中使用,并根据 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;
}
Run Code Online (Sandbox Code Playgroud)

为了将其转换为 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

}
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何返回从 for 循环产生的值。错误信息是

type mismatch;
Found   : IndexedSeq[TSourceToken]
Required: TSourceToken
Run Code Online (Sandbox Code Playgroud)

我知道yield从 for 循环中收集所有值及其内部条件并产生一个集合:IndexedSeq&因此出现错误消息。我想不出一个逻辑来形成,因为它是用 Java 代码编写的。谁能让我知道如何在 Scala 中构建代码而不使用yield并在else条件满足后中断 for 循环?

Bor*_*nov 7

for-loops在 Scala 中,java 中没有通常的东西。for-yield不一样for-loop。它只是flatMap,mapwithFilter函数组合的语法糖。同样在scala中最好不要使用return关键字。基于具有返回值和单词的表达式的语言return会破坏逻辑,这是其他开发人员无法预料的。

在您的情况下,最好使用find谓词查找某个集合中的某些特定元素:

def getBeforeToken(token: TSourceToken): TSourceToken = {
  val tokens = token.container
  val index = token.posinlist

  (index - 1 to 0 by -1)
    .find(i => tokens.get(i).toString.trim.length != 0)
    .fold(token)(i => tokens.get(i))
}
Run Code Online (Sandbox Code Playgroud)