Scala List[Unit] to List[String] conversion

200 Views Asked by At

This is a pretty basic issue but I couldn't find a solution after spending an hour on it. I'm trying to query database to get a list of values through Scala Anorm ORM. I want to convert the result to a List[String] in order to pass to a Scala view.

But It shows a compile time error

 type mismatch;
 found   : List[Unit]
 required: List[String]

This is the helper function that interacts with the Db

def getActiveConceptNames(organizationId : Long) : List[String] = {
DB.withConnection { implicit c =>
  val conceptCountQuery = SQL("select * from tbl_concepts where org_id = {org_id} and is_deleted = 0;")
    .on("org_id" -> organizationId)
  conceptCountQuery().map { conceptRecord =>
    val conceptName = conceptRecord[String]("concept_name").toString
  }.toList
}

}

And I call the helper function in the controller like this

  val conceptNamesList = ConceptHelper.getActiveConceptNames(organizationId)
1

There are 1 best solutions below

2
KArvan On

When you use the val you define a variable which is not returned (thus the Unit). Since there is a [String] I think the .toString part is no really needed. And I don't think (though I could be wrong) that you should "call" conceptCountQuery() before the map, just the variable. In addition, in a very fast skimming I did, it appears that you need to use as and a "parser" to get from the query to the actual results.

Try

conceptCountQuery.map { conceptRecord =>
  conceptRecord[String]("concept_name")
}.as(scalar.List[String])

instead of

conceptCountQuery().map { conceptRecord =>
   val conceptName = conceptRecord[String]("concept_name")
}.toList