Groovy Snippets

This is ongoing blog where i plan to record groovy code snippets that convenient, useful and powerful

Generating Long Strings

Generating certain size string( used in testing to test sized string constraints)

def genString(size){
    def nameTooLong = 'x'
    size.times { nameTooLong <<= "x" }



Avoid Exception – MissingPropertyException

There is null safe operator (?.) to avoid exceptions when calling methods on null object, however. If you call a property or method that is not defined, you will receive an exception – ‘missingPropertyException’. To make it similar as null safe but this time exception safe, add the following to your class:

def propertyMissing( name ) {

This will make call to a method, that hasn’t been defined, return null, instead throwing exception. Likewise, this will make access to a variable, that hasn’t been defined, return null instead of throwing exceptions

If you don’t have access to changing the class, then the alternative would something like:

def result = obj.hasProperty( 'b' ) ? obj.b : null

It requires much more to accomplish the same as adding the method – propertyMissing to the class only once, but it may work some situation better

 Remove last characters from string

assert 'some' == 'someString'[0..-7]

Checking if String

To determine whether its valid string, make sure check case for empty string like – ‘ ‘:

asset someString?.trim()

Leave a Reply

Your email address will not be published. Required fields are marked *