Scala:对可能返回空列表的yield的类型检查

Dot*_*tan 3 scala

我必须遵循Scala中的代码,这意味着返回句子.

val x: List[Word] = for (word <- words) yield {
  if (word.isLegit()) sentenceStartingWith(word)
}
Run Code Online (Sandbox Code Playgroud)

我收到错误,因为类型x不是,List[word]Any(因为它可能不会产生任何东西).施法没有帮助.

想到的简单修复就是

val x: List[Word] = for (word <- words) yield {
  if (word.isLegit()) sentenceStartingWith(word)
  else List[Word]()
}
Run Code Online (Sandbox Code Playgroud)

但是这将返回一个列表,其中包含许多空列表作为成员.我怎样才能获得我想要的行为,即List[word]如果找到则返回包含所有项目的行为(如果找不到则返回空)

Yuv*_*kov 7

我收到一个错误,因为x的类型不是List [word]而是Any

编译器正在推断你要做的事情.它看到的是,只有在if语句匹配时才返回一个值,因此它会隐式返回List[Any](via List.canBuildFrom[Any])与谓词不匹配的任何内容.因此,两者的共同超类型Seq[Any].

一种可能的方法是使用警卫首先过滤掉单词:

val x: List[Word] = for (word <- words if word.isLegit()) yield sentenceStartingWith(word)
Run Code Online (Sandbox Code Playgroud)

这相当于:

val x = words.withFilter(_.isLegit()).map(word => sentenceStartingWith(word))
Run Code Online (Sandbox Code Playgroud)

注意Scala中的方法是camelCase,类名是PascalCase.