Skip to content
Latchkey

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.

Jenkins console
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.castToType

Common 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

  1. Read both class names in the error to see source and target types.
  2. Wrap a scalar in a list (["main"]) or index into a collection as needed.
  3. Use def instead of a strict type when the shape is dynamic, then validate it.
Jenkinsfile
// 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/readYaml before using it.
  • Unit-test shared library helpers that return collections.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →