Avoiding usual ORM for non-relevant reasons, I'm trying to write a class that can both present data from DB and add/update data to it (is this a good idea in the first place?).
class Car (val _id:ID, val _name:String = "") {
def this(_id:ID) = {
val car = DB.fetchCar(_id)
this(_id,car.name)
}
def this(_name:String) = this(null,_name)
def isSynced:Boolean = { ... }
def sync { ... }
}
This means you can:
The thing is, the 1st constructor depends on a DB operation, thus Option[Car] as return type makes more sense. But as far as I can see Scala doesn't allow you to do something like:
def this(_id:ID):Option[Car] = {
try {
val car = DB.fetchCar(_id)
Some(this(_id,car.name))
} catch {
case e:Exception => None
}
}
Does this make sense? How would you implement this?
You can do it from the companion object of your class:
class Car private (data: CarData) {
...
}
object Car {
def apply(id: Int): Option[Car] = {
DB.find(id) match {
case Some(data) => Some(new Car(data))
case _ => None
}
}
def apply(data: CarData): Car = {
new Car(data)
}
}
This allows client code to
val someId: Int = ...
val maybeCar = Car(someId) // Will be Option[Car]
val someKnownData: CarData = ...
val definitiveCar = Car(someKnownData) // Will be Car
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With