Search code examples
scalaplayframework

How to resolve type mismatch for "Connection => [A]" with Play-JDBC?


I am building a relatively simple REST API, and I finally settled on Anorm to use for my db access library within the Play framework. However, I am having some trouble getting a basic list query to work. I am sure that this is a simple fix, but I have not been able to find any documentation / solutions for this problem. In other examples, the code is more or less doing the same thing with the query.as(parser *) function being called / returned last.

The problem is my function is (according to IntelliJ) finding a Connection => Unit type rather than my desired Connection => Seq[MyType] type. Here is my code:

case class MyType(id: Int, name: String, createdAt: LocalDateTime, updatedAt: LocalDateTime)
class MyTypeRepository @Inject()(
    dbApi: DBApi
)(implicit ec: DBExecutionContext) {
    private val db = dbApi.database("default")

    private val parser: RowParser[MyType] = {
        for {
            id <- int("mytpe.id")
            name <- str("mytype.name")
            createdAt <- get[LocalDateTime]("mytype.created_at")
            updatedAt <- get[LocalDateTime]("mytype.updated_at")
        } yield (MyType(id, name, createdAt, updatedAt))
    }

    def list(): Seq[MyType] = {
        db.withConnection { implicit conn =>
            val query = SQL("SELECT * FROM mytype")
            val result = query.as(parser *)
        } // Type mismatch error is showing up here
    }
}

Solution

  • The Anorm result is assigned to a val, rather than being returned, so the compiler appropriately infers that Unit is returned instead.

    Remove assignment to val result and so query.as(..) will be returned (instead of locally assigned).

    def list(): Seq[MyType] = {
        db.withConnection { implicit conn =>
            val query = SQL("SELECT * FROM mytype")
            query.as(parser *)
        }
    }
    

    Anorm query could be simplified as:

    def list(): Seq[MyType] = db.withConnection { implicit conn =>
      SQL"SELECT * FROM mytype".as(parser *)
    }