Brief syntax for functional composition in Scala?

I study Scala and run through the following task - if the line is empty, then return zero, otherwise in uppercase.

Apache Commons has two features that together make up the problem. In Haskell, I just write:

upperCaseOrNull = StringUtils.stripToNull . StringUtils.upperCase 

However, I cannot find a way to make the composition easy and clean in Scala. the shortest path 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, perhaps without all of these underscores?

+6
source share
2 answers

Haskell is a master of extreme compactness for a few things that really excite him. So it's almost impossible to win. If you do so many functions that invoices really bother you (I personally would have a lot more to worry about repeating StringUtils. !), You can do something like

 implicit class JoinFunctionsCompactly[B,C](g: B => C) { def o[A](f: A => B) = g compose f } 

you now have only four extra characters ( _ twice) above Haskell.

+1
source

I would not require the task to be simple if null involved. Why do you need null if None in Scala? I think that due to the return of null function is not very convenient for layout.

After converting StringUtils.stripToNull to return None for null and Some , otherwise you could use scala.Option .map and execute it with _.toUpperCase - see scaladoc for scala.Option for a discussion of this specific example.

You can also suggest something like the following:

 scala> def upperCaseOrNone = (s: String) => Option(s).fold(s) { _.toUpperCase } upperCaseOrNone: String => String 
0
source

All Articles