Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10535

IF condition on empty Collection has different behavior than null Collection

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Major
    • Resolution: Fixed
    • 3.0.10
    • 3.0.11, 4.0.3
    • None
    • None
    • Groovy 3.0.10/OpenJDK 17.0.2 - Ubuntu 21.10

    Description

      I believe this code should print "something" but doesn't work:

      @CompileStatic
      class NotWorkingExample {
        static void main(String[] args) {
          Collection<String> values = null
          for (i in 0..<200_000) {
            printSomethingIfNotEmpty(values)
          }
      
          //never printed but it should
          values = ['A']
          printSomethingIfNotEmpty(values)
        }
      
        static printSomethingIfNotEmpty(Collection<String> values) {
          if(values) {
            println 'something'
          }
        }
      }
      
      

      This one does print "something" because we pass an empty collection [] instead of null:

      @CompileStatic
      class ItWorks {
        static void main(String[] args) {
            Collection<String> values = []
            for (i in 0..<200_000) {
              printSomethingIfNotEmpty(values)
            }
      
          //it works because [] was passed in the previous 200k calls
          values = ['A']
          printSomethingIfNotEmpty(values)
        }
      
        static printSomethingIfNotEmpty(Collection<String> values) {
          if(values) {
            println 'something'
          }
        }
      }

      Some optimization is done differently when the condition is skipped too many times. Both classes should output "something" on the last method call.

      Thank you for the support.

      Attachments

        Issue Links

          Activity

            People

              emilles Eric Milles
              rodolfo.yanke Rodolfo Yanke
              Votes:
              0 Vote for this issue
              Watchers:
              7 Start watching this issue

              Dates

                Created:
                Updated:
                Resolved: