0

I have one case class.

case class Tax(state: String, code: String, pr: String, lic: String)

I am querying data from H2 database using playframework. The query returns multiple columns. Following is table structure.

Create table t(key bigint primary key, state1 varchar(10), code1 varchar(15), pr1 varchar(1), lic1 varchar(10), state2 varchar(10), code2 varchar(15), pr2 varchar(1), lic2 varchar(10), state3 varchar(10), code3 varchar(15), pr3 varchar(1), lic3 varchar(10), state4 varchar(10), code4 varchar(15), pr4 varchar(1), lic4 varchar(10));

I want to create array/list of case class and have 4 kind of rows in it.

val taxes= List[Tax]
  if (rs.next()) {
    var a=1
    while (!Option(rs.getString("state"+a)).getOrElse("").isEmpty){

      val tax = Taxonomy(rs.getString("state"+a),rs.getString("code"+a),rs.getString("pr"+a),rs.getString("lic"+a))
      //taxonomies = taxonomy Here I want to create array/list of taxonomy
      a = a + 1
      return taxonomy
    }
  }
} finally {
  conn.close()
}
2
  • First have a look at the DB libraries which are available for Commented Jul 20, 2017 at 19:23
  • Have you looked at Doobie (github.com/tpolecat/doobie)? Commented Jul 20, 2017 at 19:41

1 Answer 1

1

The comments about a DB access library are good; that would be better long-term. But might be overkill depending on your use case. Here's how I would write this directly:

val taxes = if(rs.next()) {
  (1 to 4).map { a =>
    for {
      state <- Option(rs.getString("state"+a))
      code <- Option(rs.getString("code"+a))
      pr <- Option(rs.getString("pr"+a))
      lic <- Option(rs.getString("lic"+a))
    } yield Tax(state, code, pr, lic)
  }.toList.flatten
} else {
  List.empty[Tax]
}
Sign up to request clarification or add additional context in comments.

2 Comments

When one of the element (state/code/pr/lic) is null/None, Tax in itself is coming as empty. In my scenario one column is mostly blank and because of that complete resultset is coming as null/empty
If you want to allow one of the fields to be empty, change it to an Option[String] in the case class, and replace field <- Option(...) with val field = Option(...) Good scala style is pretty adamant about not allowing nulls anywhere and using Options instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.