1

The following code

void testReference() {
    List<String> source = new ArrayList<>()
    source.add("element")
    List reference = (ArrayList)source // all ok, creates reference as types match
    assertSame(source,reference)
    List copyNotReference = (LinkedList)source // should fail on GroovyCastException, creates copy instead
    assertNotSame(source,copyNotReference) // this works, copy is a different object
    copyNotReference.add("second element")
    println source
    println copyNotReference
}

only works in Groovy. In Java it fails on attempt to cast ArrayList to LinkedList.

In Groovy it creates a LinkedList instance, calling constructor public LinkedList(Collection<? extends E> c) and copying source data to the new instance.

The test outputs

[element]
[element, second element]

That behaviour only occurs when casting types that are subtypes of collections.

Question

What Groovy mechanism is responsible for this unexpected behaviour?

0

1 Answer 1

2

Groovy allows coercion of objects via casting them (asType). This is implemented for collections.

See the source

Converts the given collection to another type. A default concrete type is used for List, Set, or SortedSet. If the given type has a constructor taking a collection, that is used. Otherwise, the call is deferred to {@link #asType(Object,Class)}. If this collection is already of the given type, the same instance is returned.

3
  • That must be it. Both standard casting via (CastTo)o, and o as CastTo use the same mechanism. What is strange is that if you use custom type C extends (some Java collection type) your custom instance is created as if it had asType implemented. But it does not and standard collection's asType is used for dataset population. Too much groovy magic!
    – vacant78
    Aug 19, 2019 at 8:12
  • If you don't like this behaviour, explicitly override asType. Otherwise you will inherit the default behaviour (it's the same "magic" as you inherit .toString())
    – cfrick
    Aug 19, 2019 at 8:32
  • I stick to my comment. I believe that most widely understood casting feature is that returned object refers to the same instance as source. With Groovy this no longer holds true, which is confusing to a VM languages programmer.
    – vacant78
    Aug 19, 2019 at 9:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.