I have a domain model that looks like this:
case class Account(id: Int, name: String)
trait BalanceTotal {
def balance: BigDecimal
}
My goal is to have a simple, lightweight Account case class and then an enhanced class Account with BalanceTotal that will only be created inside a method that does the balance calculation (which is expensive).
With this structure, I can statically ensure that I’m never counting on a balance being present when I just have a lightweight object. I know about Option, of course, but I want the type-checker to prevent code from using the lightweight object where I need the balance-enriched object, and vice-versa, and I don’t think Option gives me that.
Anyway, what I’d like to do is:
for{ Account(id,name) <- accounts } {
yield Account(id, name) with BalanceTotal {
override val balance = BigDecimal(44)
}
}
but that fails with:
';' expected but 'with' found
If I try to use new Account instead of Account, I get:
super constructor arguments cannot reference unconstructed `this`
which I assume has something to do with the voodoo that makes case classes work.
Is it possible to do what I’m trying to do?
Update: On further consideration, I guess this has something to do with the prohibition against case class inheritance. But I really do need case class magic here: I’m relying on the generated apply and unapply methods for my ScalaQuery mappings.
It works OK for me: