groovygstring

Create GString from String


We're using groovy in a type-safe way. At some point I want to invoke a method with signature

void foo(GString baa)

As long the String I enter contains some ${baz} everything is fine, but when I use a pure String I get a compile error

foo("Hello, ${baz}") // fine
foo("Hello, world") // Cannot assign value of type java.lang.String to variable of type groovy.lang.GString
foo("Hello, world${""}") // fine but ugly

Is there a nice way to create a GString out of String?

EDIT

Guess I've oversimplicated my problem. I'm using named constructor parameters to initialize objects. Since some of the Strings are evaluated lazily, I need to store them as GString.

class SomeClass {
  GString foo
}

new SomeClass(
  foo: "Hello, world" // fails
)

So method-overloading is no option.

The solution is as mentioned by willyjoker to use CharSequence instead of String

class SomeClass {
  CharSequence foo
}

new SomeClass(
  foo: "Hello, world" // works
)

new SomeClass(
  foo: "Hello, ${baa}" // also works lazily
)

Solution

  • There is probably no good reason to have a method accepting only GString as input or output. GString is meant to be used interchangeably as a regular String, but with embedded values which are evaluated lazily.

    Consider redefining the method as:

    void foo (String baa)
    void foo (CharSequence baa)  //more flexible
    

    This way the method accepts both String and GString (GString parameter is automagically converted to String as needed). The second version even accepts StringBuffer/Builder/etc.


    If you absolutely need to keep the GString signature (because it's a third party API, etc.), consider creating a wrapper method which accepts String and does the conversion internally. Something like this:

    void fooWrapper (String baa) {
        foo(baa + "${''}")
    }