Treating an SQL ResultSet like a Scala Stream

前端 未结 10 2268
天涯浪人
天涯浪人 2020-12-02 10:11

When I query a database and receive a (forward-only, read-only) ResultSet back, the ResultSet acts like a list of database rows.

I am trying to find some way to trea

10条回答
  •  孤街浪徒
    2020-12-02 10:31

    Here is an alternative, similar to Sergey Alaev's and thoredge's solutions, for when we need a solution which honors the Iterator contract where hasNext is side-effect free.

    Assuming a function f: ResultSet => T:

    Iterator.unfold(resultSet.next()) { hasNext =>
      Option.when(hasNext)(f(resultSet), resultSet.next())
    }
    

    I've found it useful to have as map "extension method" on ResultSet.

    implicit class ResultSetOps(resultSet: ResultSet) {
        def map[T](f: ResultSet => T): Iterator[T] = {
          Iterator.unfold(resultSet.next()) { hasNext =>
            Option.when(hasNext)(f(resultSet), resultSet.next())
          }
        }
      }
    

提交回复
热议问题