Jenkins "GroovyCastException: Cannot cast object" in a pipeline
Groovy tried to coerce a value into a declared type and the conversion is not valid - for example treating a single string as a List, or assigning a Map where a String was expected. The pipeline aborts with a GroovyCastException naming both types.
What this error means
The build fails with GroovyCastException: Cannot cast object '...' with class 'java.lang.String' to class 'java.util.List' (or similar), usually on an assignment or a step argument.
org.codehaus.groovy.runtime.typehandling.GroovyCastException:
Cannot cast object 'main' with class 'java.lang.String' to class 'java.util.List'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToTypeCommon causes
A scalar passed where a collection is expected
Declaring List branches = "main" or passing a single string to a step that expects a list triggers an impossible cast.
A wrong type returned from a step or helper
A function (often readJSON/readYaml or a shared library method) returns a Map or List where the caller declared a different type.
How to fix it
Match the value to the declared type
- Read both class names in the error to see source and target types.
- Wrap a scalar in a list (
["main"]) or index into a collection as needed. - Use
definstead of a strict type when the shape is dynamic, then validate it.
// wrong: List branches = 'main'
List branches = ['main']
for (b in branches) { echo b }How to prevent it
- Avoid strict static types for values whose shape depends on parsed input.
- Validate the type returned by
readJSON/readYamlbefore using it. - Unit-test shared library helpers that return collections.