ps0604 ps0604 - 13 days ago 5
Scala Question

Slick 3.1.x method returns empty list

This method uses Slick 3.1.x and it returns correctly an object of type

Future[List[Analysis]]
however the list is always empty. Why is that and how to fix this?

def readMany = {
val db = Database.forConfig("db1")
var list = new ListBuffer[Analysis]()
try {
val query = TableQuery[AnalysisDB]
val action = query.sortBy(_.name).result
val future = db.run(action).map(_.foreach {
case (analysis) => list += Analysis ( analysis.sk, analysis.name )
})
Future { list.toList }
} finally db.close
}

Answer

The list is being returned before it is populated. Your val future (database call) is being ignored/discarded, and a Future(list) (still empty) returned. Try this;

def readMany = {
  val db = Database.forConfig("db1")
  try {
    val query = TableQuery[AnalysisDB]
    val action = query.sortBy(_.name).result
    db.run(action).map(_.map {
      a => Analysis(a.sk, a.name)
    })
  } finally db.close
}

This also avoids the smelly mutable ListBuffer.