Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an instance is of type String or GString in Groovy

Tags:

types

groovy

I would like to learn what the robust way of checking, if a variable is of type string or gstring, is. I suppose it is different than in pure Java:

def var = someFunc();  if (var instanceof String || var instanceof GString) {    String str = var; } 

I ask, because I do not want to be surprised that I have missed a Groovy specific feature that causes a hard to debug bug.

like image 883
Skarab Avatar asked Jun 16 '11 21:06

Skarab


People also ask

How do I know the type of variable in Groovy?

You can use the getClass() method to determine the class of an object. Also, if you want to check if an object implements an Interface or Class, you can use the instanceof keyword. That's it about checking the datatype of an object in Groovy.

What does == mean in Groovy?

Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a. compareTo(b)==0, if they are Comparable, and a. equals(b) otherwise.

What is a GString in Groovy?

Class GString Represents a String which contains embedded values such as "hello there ${user} how are you?" which can be evaluated lazily.

Does == work in Groovy?

== is symmetric in groovy. While that table is super handy, it's a bit misleading as == isn't actually on it.


1 Answers

Instanceof tests should work:

assert "fasd" instanceof String assert "${this}" instanceof GString 
like image 122
Andrew Eisenberg Avatar answered Sep 19 '22 10:09

Andrew Eisenberg