In this post we’ll look at
StringOps and the goodies it provides to work with
Strings. Like we did last time, we’ll jump straight into examples.
@ import scalaz._
Scalaz provides a convenient
plural method on
String to get its plural form. Going over the docs for
Returns the same String value if the given value is 1 otherwise pluralises this String by appending an “s” unless this String ends with “y” and not one of [“ay”, “ey”, “iy”, “oy”, “uy”] in which case the ‘y’ character is chopped and “ies” is appended.
This explains why the plural of “dress” was “dresss” with 3 “s”;
plural simply appended an “s”. Nonetheless, this is a convenient method.
@ "list" charsNel
charsNel converts the
String into an
Option[NonEmptyList[Char]]. This method is useful if the string represents a sequence of actions to be taken as characters. For example, “OCOC” could mean “Open, Close, Open, Close” or something and
charsNel would convert this into an
NonEmptyList[Char]. You can then iterate over the characters and take whatever action you want to.
Scalaz provides convenient methods for parsing a
Int, etc. The advantage of using these over standard Scala parsing methods is that these methods return a
Validation. You can then fold the
Validation object to see whether the value was successfully parsed or resulted in an error. This is good for functional programming as you don’t have to catch exceptions. We’ll first look at the Scala way and then the Scalaz way.
// Scala way
It’s also possible to parse values to
@ "3.14159265358979323846".parseBigDecimal.fold(err => "failed parse".println, num => num.println)
This covers the convenience methods Scalaz provides for dealing with
parseXXX methods are the most useful as they avoid having to deal with an exception.