Groovy List.contains / GString fuss

If you want to search for String value in the List using contains method, be careful if the argument is GString type.

  1.  
  2. def foo = 1
  3. assert !['1','2','3'].contains("${foo}")
  4. assert ['1','2','3'].contains("${foo}".toString())
  5.  

Why? Because contains use equals method to match your parameter to each position on the list, and for equals we have:

  1.  
  2. def foo = "groovy"
  3. def bar = "groovy${''}"
  4.  
  5. assert foo.class == java.lang.String
  6. assert bar.class == org.codehaus.groovy.runtime.GStringImpl
  7.  
  8. assert foo == bar
  9. assert bar == foo
  10. assert !foo.equals(bar)
  11. assert !bar.equals(foo)
  12.  

No Comments yet

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.