Search code examples
scalascala-java-interop

unable to convert a java.util.List into Scala list


I want that the if block returns Right(List[PracticeQuestionTags]) but I am not able to do so. The if/else returns 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)}

Solution

  • Change the java.util.List list to a Scala List as soon as possible. Then you can handle it in Scala fashion.

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