Skip to content

Instantly share code, notes, and snippets.

@irajhedayati
Last active November 19, 2020 21:48
Show Gist options
  • Save irajhedayati/6759bc6cf4ec69fb22da6ab7ddcb8693 to your computer and use it in GitHub Desktop.
Save irajhedayati/6759bc6cf4ec69fb22da6ab7ddcb8693 to your computer and use it in GitHub Desktop.
Scala cheatsheet
// How to convert a JDBC iterator to a Scala iterator
/* A data model to reflect the content of ResultSet */
case class Movie(mId: Int, title: String, rId: Int, ratingDate: String)
import java.sql.{ ResultSet, Statement }
val stmt: Statement = ???
val rs: ResultSet = statement.executeUpdate("SELECT * FROM movie".stripMargin)
// 1. Wrap it around a Scala iterator; it is more flexible
val itr1: Iterator[Movie] = new Iterator[Movie] {
override def hasNext: Boolean = rs.next()
override def next(): Movie = new Movie(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4))
}
// 2. Use `continually`; it is more compact and easy
val itr2: Iterator[Movie] =
Iterator.continually(rs).takeWhile(_.next()).map(rs => Movie(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getString(4)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment