Re: Groovy truth and casting to boolean
Ondra Cada <[email protected]>
| Newsgroups | gmane.comp.lang.groovy.devel |
|---|---|
| Message-ID | <[email protected]> |
Jochen, for my tuppence worth, I'd prefer “always use asBoolean”, at the very least very definitely in the dynamic mode (it may be perhaps argued that with CompileStatic the user might accept inconsistencies when it might bring some extra speed). Thanks and all the best, OC > On 19. 1. 2026, at 13:52, Jochen Theodorou <[email protected]> wrote: > > Hi, > > One of the next things I will look into with invokedynamic is surely the casting too boolean using invokedynamic.But I have the feeling something is off here. > > If we have an expression > > if (foo) m() > > then m() will be called if foo can be converted to boolean true, also known as Groovy Truth(ness). From a runtime perspective the rules are easy, just expand it to foo.asBoolean(). But that is not how we compile this. Instead if we know the type of foo and it satisfies certain conditions we shortcut. > > * foo static type is boolean => do nothing > * foo static type is other primitive => convert directly in bytecode. > * foo runtime value is null => false > * other cases call asBoolean() > > This means we can replace the asBoolean method on everything except null and primitives. We do this mostly for efficiency reasons. Of and there is the specialty that asType(Boolean) falls back to asBoolean basically. Which makes sense, though a cleaner solution would probably have been to always use asType... of course more complicated performance wise as well.. possibly. > > My question is though if we want to keep this mixed cases. Alternatives would be: > > * always use asBoolean > * exempt asBoolean from replacement in meta classes > > > > bye Jochen