Skip to content

Commit

Permalink
GROOVY-11151: Example in the Documentation of the Coercion Operator i…
Browse files Browse the repository at this point in the history
…s Wrong
  • Loading branch information
paulk-asert committed Aug 8, 2023
1 parent 5c2aed0 commit 4141f2b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
4 changes: 2 additions & 2 deletions src/spec/doc/core-operators.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -816,15 +816,15 @@ 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:
[source,groovy]
----
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
Expand Down
12 changes: 7 additions & 5 deletions src/spec/test/OperatorsTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
Expand Down

0 comments on commit 4141f2b

Please sign in to comment.