Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*in* keyword with String in Groovy

Tags:

groovy

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.

like image 361
aa8y Avatar asked Nov 18 '14 21:11

aa8y


People also ask

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I manipulate strings in Groovy?

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.

How do I use Groovy in keyword?

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.

What is ${} in Groovy?

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 ${} .


1 Answers

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.

like image 155
christopher Avatar answered Sep 24 '22 03:09

christopher