【问题标题】:unable to convert a java.util.List into Scala list无法将 java.util.List 转换为 Scala 列表
【发布时间】:2020-09-26 08:17:52
【问题描述】:

我希望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)}

【问题讨论】:

标签: scala scala-java-interop


【解决方案1】:

尽快将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)

【讨论】:

    【解决方案2】:

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

    实现此目的的一种方法是使用 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)
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-16
      • 2011-10-22
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多