Search code examples
scalaplayframeworkplayframework-2.3anorm

Converting Pk[Long] to Option[Long] in a Form


I have been having trouble understanding what the issue is here since the Scala Anorm Pk became deprecated.

I switched my model to the following:

case class Item(id: Option[Long] = NotAssigned,
            title: String,
            descr: String,
            created: Option[Date],
            private val imgs: List[Img],
            private val tags: List[Tag]) 

From id: Pk[Long]

I changed my form to:

val itemForm = Form(
    mapping(
      "id" -> ignored(23L),
      "title" -> nonEmptyText,
      "descr" -> nonEmptyText,
      "created" -> optional(ignored(new Date)),
      "imgs" -> Forms.list(itemImgs),
      "tags" -> Forms.list(itemTags)
    )(Item.apply)(Item.unapply)
)

From "id" -> ignored(NotAssigned:Pk[Long])

But, I get this error.

type mismatch; found : (Option[Long], String, String, scala.math.BigDecimal, Option[java.util.Date], List[models.Img], List[models.Tag]) => models.Item required: (Long, String, String, Option[java.util.Date], List[models.Img], List[models.Tag]) => ? )(Item.apply)(Item.unapply)

Why is an Option[Long] not required on the Item model?

I don't know what 23L is, but that's what was in the Play Documentation. The value of id in the database is coming from a sequence.

If I change it to:

"id" -> ignored(NotAssigned:Option[Long]),

Which makes the most sense to me... I get this error:

type mismatch; found : anorm.NotAssigned.type required: Option[Long] "id" -> ignored(NotAssigned:Option[Long]),

Which makes less sense than before.


Solution

  • Just to clarify, it's not Anorm that's deprecated, but the Pk type within Anorm.

    Your problem here is that you're trying to assign NotAssigned to an Option[Long], which is incompatible. You should change all of the NotAssigneds to None.

    So your class would look like this:

    case class Item(
        id: Option[Long] = None,
        title: String,
        descr: String,
        price: BigDecimal,
        created: Option[Date],
        private val imgs: List[Img],
        private val tags: List[Tag]
    ) 
    

    And the Form mapping:

    "id" -> ignored[Option[Long]](None)