Scala: Setting a default value
We wanted to try and generate a build label to use for the name of the artifacts archive that gets generated each time we run the build but wanted to default it to a hard coded value if the system property representing the build label wasn’t available.
In Ruby we would be able to do something like this:
buildLabel = ENV["GO_PIPELINE_LABEL"] || "LOCAL"
There isn’t a function in Scala that does that so we initially ended up with this:
def buildLabel() = [{
System.getenv("GO_PIPELINE_LABEL") match {
case null => "LOCAL"
case label => label
}
}
My colleague Mushtaq suggested passing the initial value into an Option like so…
def buildLabel() = {
Option(System.getenv("GO_PIPELINE_LABEL")).getOrElse("LOCAL")
}
…which I think is pretty neat!
I tried to see what the definition of an operator to do it the Ruby way would look like and ended up with the following:
class RichAny[A](value:A ) {
def || (default:A ) = { Option(value).getOrElse(default) }
}implicit def any2RichAny[A <: AnyRef](x: A) = new RichAny(x)
Which we can use like so:
def buildLabel() = {
System.getenv("GO_PIPELINE_LABEL") || "LABEL"
}I imagine that’s probably not the idiomatic Scala way to do it so I’d be curious to know what is.
From http://www.markhneedham.com/blog/2011/06/12/scala-setting-a-default-value/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)






Comments
Erik Post replied on Mon, 2011/06/13 - 6:05am
Erwin Mueller replied on Mon, 2011/06/13 - 2:30pm
I choose the Java way:
buildLabel= System.getenv("GO_PIPELINE_LABEL")if (buildLabel==null) { buildLabel = "LOCAL"; }
That way I can still understand it 2 weeks later.
I'm all for new languages and stuff, but do Scala developers have nothing better to do as to try to invent the most cryptic code possible?
Who can get more cryptic code?
class RichAny[A](value:A ) { def || (default:A ) = { Option(value).getOrElse(default) } }
implicit def any2RichAny[A <: AnyRef](x: A) = new RichAny(x)
def buildLabel() = { System.getenv("GO_PIPELINE_LABEL") || "LABEL" }
Cloves Almeida replied on Mon, 2011/06/13 - 7:24pm
in response to:
Erwin Mueller
Scala have an unnatural tendency to use symbols where words would be a better match.
Why not the SQLish:
import static myapp.NullUtils.* ... buildLabel = coalesce(System.getenv("GO_PIPELINE_LABEL"),"LOCAL");Erik Post replied on Thu, 2012/05/24 - 5:51pm
in response to:
Erwin Mueller
implicit class RichAny[A](value:A) {