I'm learning Scala and ran across the following task - if string is blank then return null, otherwise uppercase it.
There are two functions in Apache Commons that composed together solves the problem. In Haskell I'd just write:
upperCaseOrNull = StringUtils.stripToNull . StringUtils.upperCase
However I can't find a way to do an easy and clean function composition in Scala. the shortest way I found is as follows:
def upperCaseOrNull (string:String) = StringUtils.stripToNull (StringUtils.upperCase(string))
def upperCaseOrNull = StringUtils.stripToNull _ compose StringUtils.upperCase _
Does Scala offer a more concise syntax, possibly without all those underscores?
It is possible to make composition slightly more compact:
Using
andThen
To get it down to a single underscore (even with more than two functions composed):
More general case with three functions:
Using a helper function
If
f
,g
andh
are functions taking oneString
parameter and returning aString
:Where the
composeMany
function looks like this:Haskell is a master of extreme compactness for a few things it really cares about. So it's pretty much impossible to beat. If you are doing so much function composition that the overhead really gets in your way (personally, I'd be a lot more troubled by repeating
StringUtils.
!), you can do something likeso now you only have four extra characters (
_
twice) over Haskell.I wouldn't claim a task be simple if
null
's are involved. Why would you neednull
ifNone
in Scala would do? I think that due tonull
being returned the function is not very compose-friendly.Once you transform
StringUtils.stripToNull
to returnNone
fornull
andSome
otherwise, you could then use scala.Option.map and execute it with_.toUpperCase
- see the scaladoc for scala.Option where this particular example is discussed.One might also suggest something as follows: