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

312 Views Asked by At

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)}
2

There are 2 best solutions below

0
On BEST ANSWER

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)
0
On

Your finalList: List[PracticeQuestionTag] = List() is immutable scala list. So you can not change it, meaning there is no way to add, remove or do change to this list.

One way to achieve this is by using scala functional approach. Another is using a mutable list, then adding to that and that list can be final value of if expression.

Also, a while expression always evaluates to Unit, it will never have any value. You can use while to create your answer and then return it seperately.

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)
}