In Scala you often use Java APIs which use the Builder pattern, e.g Google Maps Java Client (used in the example below).
I use a Scala case class in our app to gather all values that I will use then for the Builder pattern of the Java API. I design optional values of the Builder API, idiomatically with Scalas Option type. However I scratch my head how to do this nicer than this example:
case class WlanHint(
mac: String,
signalStrength: Option[Int],
age: Option[Int],
channel: Option[Int],
signalToNoiseRatio: Option[Int]
)
val builder = WifiAccessPoint.WifiAccessPointBuilder().MacAddress(wlanHint.mac)
val b = wlanHint.signalStrength.map(signalStrength => builder.SignalStrength(signalStrength)).getOrElse(builder)
val b2 = wlanHint.age.map(age => b.Age(age)).getOrElse(b)
val b3 = wlanHint.channel.map(channel => b2.Channel(channel)).getOrElse(b2)
val b4 = wlanHint.signalToNoiseRatio.map(signalToNoiseRatio => b3.SignalToNoiseRatio(signalToNoiseRatio)).getOrElse(b3)
// TODO is there a better way to do this above?
b4.createWifiAccessPoint())
You can hide the builder calls within the
case classas methods and also (since a Java builder is typically mutable) use theforeachmethod onOption:The first
foreachin this example ends up being effectively the same as:If
WlanHintis only intended to reify the arguments to the builder, it might make sense to have it be aFunction0[WifiAccessPoint]:This would then allow you to write: