문제

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.

도움이 되었습니까?

해결책

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")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top