Library contents

Groovy String.transform

Pass a string to a function and return the result produced by that function.

A simple example

String.transform

  1. Start with "12"
  2. Do this Transform text by parsing it
  3. Result 12 as a number
The supplied function receives the string and supplies the return value.

Syntax

Groovy 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.groovy

Parse 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.

Result18
Lesson.groovy
println " 17 ".strip().transform { s -> Integer.parseInt(s) + 1 }
Output
18

The transformation returns a numeric result.

Advertisements

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.

Result[Lab]
Lesson.groovy
println "Lab".transform { s -> "[" + s + "]" }
Output
[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?

Given“18” + 2 on hand
Worked result20

What to watch for

The result may have a different type. Parsing and other supplied functions can throw their own exceptions.

Documentation for String.transform