Frage

I'm creating some case classes in Scala that I use to persist data mongodb. The client app is written in Java and using my repository by passing in instances of these case classes.

It works fine, unless I use optional fields:

case class Person (name: String, email: Option[String])

Now from Java I don't want to reference Scala's Option, so I'd prefer to override a constructor that allows the client to call something like

new Person("Jack", "jack@ripper.com");

A factory method on the companion object would also be OK. I'm looking for a solution that allows me to write Java without any scala deps, preferably no more convoluted than calling a constructor. Thoughts?

War es hilfreich?

Lösung

Why is this insufficient?

case class Person (name: String, email: Option[String]) {
    def this(name: String, email: String) {
        this(name, Option(email))
    }
}

Surely, it still uses Option[String], but it remains invisible to the client. The only problem is that the Java client code will still see both constructors.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top