apple/pkl · error
cannotParseStringAs
cannotParseStringAs
Error message
cannotParseStringAs
What it means
Thrown by String.toInt() when the string cannot be parsed as an integer. Pkl uses Java's integer parsing (after removing underscores), so any non-integer text — including floats, hex without prefix support, or surrounding whitespace — raises this error with the offending string attached.
Solutions
- Trim and validate the string contains only an optional sign and digits before calling toInt
- Use toFloat() first if the value may be decimal, then convert
- Provide a default: `s.toIntOrNull() ?? default` if available in your Pkl version
- Reject or sanitize commas/separators before parsing
Example fix
// before
val n = userInput.toInt()
// after
val n = userInput.trim().replace(",", "").toIntOrNull() ?? 0 Defensive patterns
Strategy: validation
Validate before calling
function isIntString(s: String): Boolean = s.trim().isRegexMatch(/^[+-]?\d+$/, _)
Prevention
- Trim and validate numeric strings before parsing
- Use toIntOrNull with a fallback default
- Watch for thousand separators and whitespace from external data
When it happens
Trigger: Calling `"abc".toInt()`, `"3.14".toInt()`, `" 42 ".toInt()` (whitespace not trimmed), or an empty string; also integers out of the 64-bit Long range.
Common situations: Reading values from config files, environment variables, or user input assumed numeric; decimals coming from JSON/YAML strings; localized numbers with separators.
Related errors
- adhocEvalError
- Cannot convert pkl.base#String
- cannotParseCertFile
- charIndexOutOfRange
- charIndexOutOfRange
AI-assisted analysis of apple/pkl@f3efcbfc9b (2026-09-08).
Data as JSON: /api/errors/b1a3a9d1807b78f7.
Report an issue: GitHub.
Appendix: source
Thrown at pkl-core/src/main/java/org/pkl/core/stdlib/base/StringNodes.java:888
// ensure no trailing garbage
if (lexer.next() != Token.EOF) {
throw new NumberFormatException();
}
return parsed;
} catch (ParserError ignored) {
throw new NumberFormatException();
}
}
public abstract static class toInt extends ExternalMethod0Node {
@TruffleBoundary
@Specialization
protected long eval(String self) {
try {
return toInt(self);
} catch (NumberFormatException e) {
throw exceptionBuilder()
.evalError("cannotParseStringAs", "Int")
.withProgramValue("String", self)
.build();
}
}
}
public abstract static class toIntOrNull extends ExternalMethod0Node {
@TruffleBoundary
@Specialization
protected Object eval(String self) {
try {
return toInt(self);
} catch (NumberFormatException e) {
return VmNull.withoutDefault();
}
}
}View on GitHub (pinned to f3efcbfc9b)