无法将java.util.List转换为Scala列表



我希望if块返回Right(List[PracticeQuestionTags]),但我不能这样做。if/else返回Either

//I get java.util.List[Result]
val resultList:java.util.List[Result] = transaction.scan(scan);
if(resultList.isEmpty == false){
val listIterator = resultList.listIterator()
val finalList:List[PracticeQuestionTag] = List()
//this returns Unit. How do I make it return List[PracticeQuestionTags]
val answer = while(listIterator.hasNext){
val result = listIterator.next()
val convertedResult:PracticeQuestionTag = rowToModel(result) //rowToModel takes Result and converts it into PracticeQuestionTag
finalList ++ List(convertedResult) //Add to List. I assumed that the while will return List[PracticeQuestionTag] because it is the last statement of the block but the while returns Unit
}
Right(answer) //answer is Unit, The block is returning Right[Nothing,Unit] :(
} else {Left(Error)}

尽快将java.util.List列表更改为ScalaList。然后你就可以用Scala的方式处理它了。

import scala.jdk.CollectionConverters._
val resultList = transaction.scan(scan).asScala.toList
Either.cond( resultList.nonEmpty
, resultList.map(rowToModel(_))
, new Error)

您的finalList: List[PracticeQuestionTag] = List()immutable标量列表。因此,您不能更改它,这意味着无法添加、删除或更改此列表。

实现这一点的一种方法是使用scala函数方法。另一种是使用mutable list,然后添加到该列表中,该列表可以是if表达式的最终值。

此外,while表达式的计算结果始终为Unit,它永远不会有任何值。您可以使用while创建您的答案,然后单独返回。

val resultList: java.util.List[Result] = transaction.scan(scan)
if (resultList.isEmpty) {
Left(Error)
}
else {
val listIterator = resultList.listIterator()
val listBuffer: scala.collection.mutable.ListBuffer[PracticeQuestionTag] = 
scala.collection.mutable.ListBuffer()
while (listIterator.hasNext) {
val result = listIterator.next()
val convertedResult: PracticeQuestionTag = rowToModel(result)
listBuffer.append(convertedResult)
}
Right(listBuffer.toList)
}

最新更新