Reputation: 111
Why these two strings are not matching on neither one: .equals() OR .compareTo() OR == OR Objects.equals()? I believe it should match atleast at one comparions.
Process proc1 = 'cat /home/output.txt'.execute()
Process proc2 = 'grep -o -m 1 webServiceReturn'.execute()
Process all = proc1 | proc2
def log = all.text.toString()
String svc = "webServiceReturn";
println (log)
println (svc)
//if (svc.equals(log)) {
//if (svc.compareTo(log)) {
//if(svc == log) {
if (Objects.equals((svc),(log))) {
println "MATCHED" }
else {
println "NOT MATCHED" }
The result on all four comparison are:
webServiceReturn
webServiceReturn
NOT MATCHED
Upvotes: 2
Views: 10081
Reputation: 1225
I just learned from another StackOverflow answer that using equals()
, .contains
and in
fail to see same contents of strings of different type.
Groovy different results on using equals() and == on a GStringImpl
According to an answer by @dunes in the above question, the Groovy comparison using ==
uses compareTo()
opportunistically before equals()
. (The ==
comparison in Groovy has a remarkable difference from Java where it compares references).
def expandedString = "${'test'}"
def simpleString = 'test'
println "Expansion: ${expandedString}"
println "equals 'test' ? ${expandedString.equals(simpleString)}"
println " == 'test' ? ${expandedString == simpleString}"
The above outputs the following,
Expansion: test
equals 'test' ? false
== 'test' ? true
The following excerpt from the Groovy documentation omits the compareTo()
piece that makes ==
different from equals()
.
In Groovy, using
==
to test equality is different from using the same operator in Java. In Groovy, it is calling equals. If you want to compare reference equality, you should useis
like in the following example:def list1 = ['Groovy 1.8','Groovy 2.0','Groovy 2.3']
def list2 = ['Groovy 1.8','Groovy 2.0','Groovy 2.3']
assert list1 == list2
assert !list1.is(list2)
http://docs.groovy-lang.org/next/html/documentation/core-operators.html#_identity_operator
Upvotes: 0
Reputation: 7868
I was able to reproduce your issue and making one minor modification to trim the white space on the results allowed it to match.
Do a trim on your all.text to remove any extraneous white space.
def log = all.text.trim()
You don't need the .toString() call either.
Upvotes: 4