This is an automated email from the ASF dual-hosted git repository.
paulk pushed a commit to branch GROOVY_3_0_X
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/GROOVY_3_0_X by this push:
new 4141f2b00c GROOVY-11151: Example in the Documentation of the Coercion
Operator is Wrong
4141f2b00c is described below
commit 4141f2b00ccdad27cbcc44c7c71b361b68b6b89e
Author: Paul King <[email protected]>
AuthorDate: Tue Aug 8 14:07:46 2023 +1000
GROOVY-11151: Example in the Documentation of the Coercion Operator is Wrong
---
src/spec/doc/core-operators.adoc | 4 ++--
src/spec/test/OperatorsTest.groovy | 12 +++++++-----
2 files changed, 9 insertions(+), 7 deletions(-)
diff --git a/src/spec/doc/core-operators.adoc b/src/spec/doc/core-operators.adoc
index 81b71e166f..eb977dac55 100644
--- a/src/spec/doc/core-operators.adoc
+++ b/src/spec/doc/core-operators.adoc
@@ -816,7 +816,7 @@ being compatible for assignment. Let's take an example:
----
include::{projectdir}/src/spec/test/OperatorsTest.groovy[tags=coerce_op_cast,indent=0]
----
-<1> `Integer` is not assignable to a `String`, so it will produce a
`ClassCastException` at runtime
+<1> `String` is not assignable to an `Integer`, so it will produce a
`ClassCastException` at runtime
This can be fixed by using _coercion_ instead:
@@ -824,7 +824,7 @@ This can be fixed by using _coercion_ instead:
----
include::{projectdir}/src/spec/test/OperatorsTest.groovy[tags=coerce_op,indent=0]
----
-<1> `Integer` is not assignable to a `String`, but use of `as` will _coerce_
it to a `String`
+<1> `String` is not assignable to an `Integer`, but use of `as` will _coerce_
it to an `Integer`
When an object is coerced into another, unless the target type is the same as
the source type, coercion will return a
*new* object. The rules of coercion differ depending on the source and target
types, and coercion may fail if no conversion
diff --git a/src/spec/test/OperatorsTest.groovy
b/src/spec/test/OperatorsTest.groovy
index 7b0c9b02ec..d58ab17db2 100644
--- a/src/spec/test/OperatorsTest.groovy
+++ b/src/spec/test/OperatorsTest.groovy
@@ -627,15 +627,17 @@ assert function(*args,5,6) == 26
void testCoercionOperator() {
try {
// tag::coerce_op_cast[]
- Integer x = 123
- String s = (String) x // <1>
+ String input = '42'
+ Integer num = (Integer) input // <1>
// end::coerce_op_cast[]
+ assert false, 'Should not reach here but instead should have
thrown a ClassCastException'
} catch (ClassCastException e) {
+ assert e.message == "Cannot cast object '42' with class
'java.lang.String' to class 'java.lang.Integer'"
// tag::coerce_op[]
- Integer x = 123
- String s = x as String // <1>
+ String input = '42'
+ Integer num = input as Integer // <1>
// end::coerce_op[]
- assert s == '123'
+ assert num == 42
}
assertScript '''
// tag::coerce_op_custom[]