I need a builder library that can be called from Scala and Java. Easy enough in Scala using default, named parameters. But how do I call this code from Java? See below. Or perhaps I should go with a fluent API that is more common to both languages?
Scala:
case class Person(gender:Gender.Value, firstName:String, lastName:String){
def fullName = lastName+", "+firstName
override def toString = firstName+","+lastName+","+gender
}
case class PersonBob(
gender:Gender = GenderBob().build,
firstName:String = null,
lastName:String = null) {
def build = Person(
gender,
if(firstName == null) NameBob(if(gender==Gender.Male) engMaleNames
else engFemaleNames).build else firstName,
if(lastName==null) NameBob(engLastNames).build
else lastName
)
}
Usage:
val p1 = PersonBob().build
val p2 = PersonBob(lastName = "Jones").build
Java Usage:
Person p1 = ?
Person p2 = ?
default arguments are not interoperable between scala and java, as mentioned in the very last statement from http://www.scala-lang.org/node/2075.
to determine how to use your above code from java, perhaps javap can help. let's take a smaller example than what you have posted. for instance
compiling this using scalac, and then running javap on the produced class file (without the .class extension), we get
we can see that the only constructor we have is
so in your case, your java code would look something like
assuming the GenderBob class takes no parameters in its constructor. as for how fluent this in in Java, i suppose ultimately it is a matter of taste, but in my humble opinion i think the Java version could be less verbose for a builder