如何解决无法将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
列表更改为Scala List
。然后,您可以以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)
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。