groovy:000> 'hello' in 'hello world'
===> false
groovy:000> 'hello world'.contains('hello')
===> true
groovy:000> 'hello' in ['hello', 'world']
===> true
groovy:000> ['hello', 'world'].contains('hello')
===> true
Now, shouldn't the in keyword imitate contains for String like it does for List? Is it a bug or is it how it's supposed to be? I am using Groovy 2.3.7.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
A String literal is constructed in Groovy by enclosing the string text in quotations. Groovy offers a variety of ways to denote a String literal. Strings in Groovy can be enclosed in single quotes ('), double quotes (“), or triple quotes (“””). Further, a Groovy String enclosed by triple quotes may span multiple lines.
The in keyword is sometimes used in Groovy to ascertain whether an object is contained within a collection. A nice example of this is demonstrated in the post The Groovy 'in' Keyword. The in keyword is often used in Groovy in conjunction with iteration/looping.
String interpolation. Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} .
The in keyword works on Collection types; not on String types.
Why does String to String Comparison work?
Groovy in operator depends on the isCase method. It will use that in comparison. The String isCase method uses equals to perform this comparison. Obviously hello is not equal to hello world, ergo it returns false. However, hello does equal hello, ergo true.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With