Search code examples
scalasorm

SORM Persisted 'id' undefined


I am just trying to learn SORM and am playing with what I think is some simple sample code. To whit:

case class Book(var author:String, var title:String);

object Db extends Instance(
  entities = Set(Entity[Book]()),
  url = "jdbc:h2:mem:test",
  user = "",
  password = "",
  initMode = InitMode.Create
)

And then:

val b : Book with Persisted = Db.save( Book("foo","bar")  )

When attempting to compile this, I get:

[error] /Users/rjf/IdeaProjects/PlayTest/app/controllers/Application.scala:22: type mismatch;
[error]  found   : models.Book
[error]  required: sorm.Persisted with models.Book
[error]     val b : Book with Persisted = Db.save( Book("foo","bar")  )
[error]                                                ^

If I change the Book declaration to:

case class Book(var author:String, var title:String) extends Persisted;

I then get:

[error] /Users/rjf/IdeaProjects/PlayTest/app/models/Book.scala:17: class Book needs to be abstract, since:
[error] it has 2 unimplemented members.
[error] /** As seen from class Book, the missing signatures are as follows.
[error]  *  For convenience, these are usable as stub implementations.
[error]  */
[error]   def id: Long = ???
[error]   def mixoutPersisted[T]: (Long, T) = ???
[error] case class Book(var author:String, var title:String) extends Persisted;
[error]            ^

Apologies for the newbie question. No doubt that the fact I'm learning Scala at the same time is a contributing factor.


Solution

  • To solve your issue, just remove the explicit type annotation:

    val b = Db.save( Book("foo","bar") )
    

    Don't worry, you'll still be able to access the same interface as Book with Persisted.

    As to why this happens, this seems to be a bug of Scala, and it's been reported.

    A sidenote

    Don't use vars in case class declaration. Immutability is the whole point of case classes. The correct declaration would be:

    case class Book(author:String, title:String)
    

    which is the same as

    case class Book(val author:String, val title:String)