Question

I have noticed some conflict between implicit constructor and GroovyTruth.

Consider following code

assert new File('/') == ['/'] as File
assert Boolean.TRUE == ["false"] as Boolean

First line is implict call of File(String) constructor. Second line simply returns true, because list is not empty. But it can(should?) call Boolean(String) constructor with different result value(false).

Is it bug, documented feature or smth. else? Should I report it as bug?

Was it helpful?

Solution

When you do:

['false'] as Boolean

It ends up going through DefaultTypeTransformation.castToType, which calls castToBoolean which as you can see checks for null, then calls asBoolean on the Collection type which just checks it's not empty

With the File example, it falls through to the bottom of castToType and just tries to invoke the constructor with the contents of the list

I wouldn't say this is a bug, but it's definitely an idiosyncrasy of Groovy that has to be taken in to account (and changing it now would be a massive break with compatibility)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top