Reputation: 730
I'm relatively new to Scala, and am trying to code some basic object-relational mapping for a hobby project. I have classes representing my application domain objects, for example:
class Employee(val name:String)
I would like my ORM layer to record the database key with this employee, but this should not clutter the public Employee class. I thought I could use a trait for this:
trait DBEntity {val id:Int}
Within my ORM layer, when an employee is queried, I would return:
new Employee("Bob") with DBEntity {val id=5}
This will allow my ORM layer to later retrieve the id for an employee. My questions are:
1) Is this the best way to mix-in the trait? It boils down to creating an inline anonymous class, I would have preferred something like new Employee("Bob") with DBEntity(5)
, but traits can't have constructor parameters so this won't compile.
2) I am considering making Employee a case class to aid matching later on, would the new anonymous subclass returned by the ORM layer still be suitable for matching?
Upvotes: 1
Views: 98
Reputation: 49685
This is certainly valid, but you might find it cleaner to have Employee
subclass DBEntity
. In this case you'd possibly want to make the id
field a def
in the trait and override it with a val
in the Employee
class.
Either way, pattern matching will work on the case class.
Upvotes: 1