Groovy String.transform
Pass a string to a function and return the result produced by that function.
A simple example
String.transform
- Start with "12"
- Do this Transform text by parsing it
- Result 12 as a number
Syntax
public <R> R transform(Function<? super String,? extends R> f)
Run these examples in Groovy
Save one example at a time as Lesson.groovy. Use Groovy 4 on JDK 21.
groovy Lesson.groovyParse form capacity
A booking form supplies a capacity or party size before a room can be assigned. Check the value at that boundary so the booking logic can work with a usable number of places.
println " 17 ".strip().transform { s -> Integer.parseInt(s) + 1 }
18
The transformation returns a numeric result.
Decorate a course name
A display component receives text through a general-purpose interface. Convert or transform the supplied value at the boundary where the component needs the final printable label.
println "Lab".transform { s -> "[" + s + "]" }
[Lab]
The transformation can also produce another String.
Read the afternoon delivery
A store receives a quantity as text from a barcode reader. Read the whole decimal quantity and add it to the two units already at the desk. What total should the register show?
What to watch for
The result may have a different type. Parsing and other supplied functions can throw their own exceptions.