Frage

I am kind of new to scala and have not done any programming in java or object oriented programming languages.

I have been using this case class to write to the database

case class User(id: new ObjectId, name: String)

What is the best way to let this accept either an ObjectId String, or an ObjectId? Ideally I would like to just have the case class implicitly convert a string to an ObjectId.

War es hilfreich?

Lösung

You should go for a companion object and a case class eg:

object User {
    def apply(name: String): User = User(new ObjectId(), name)

    def apply(id: String, name: String): User = User(new ObjectId(id), name)
}

case class User(id: ObjectId, name: String)

Then you can handle either these cases:

val user = User("Ross")
val user1 = User("5204b74d9932e8319b8e9ec0", "Ross")
val user2 = User(new ObjectId(), "Whitehead")
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top