Arpit Shah
Arpit Shah

Reputation: 157

Scala Array of Case Class

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

Upvotes: 0

Views: 1551

Answers (1)

Joe K
Joe K

Reputation: 18434

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

Upvotes: 1

Related Questions