0

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
)
mibutec
  • 2,929
  • 6
  • 27
  • 39

2 Answers2

1

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 + "${''}")
}
willyjoker
  • 787
  • 6
  • 16
0

You can create overloaded methods or you can use generics; something as below:


foo("Hello from foo GString ${X}")
foo("Hello from foo")

MyClass.foo("Hello from foo GString ${X}")
MyClass.foo("Hello from foo")

// method with GString as parameter
void foo(GString g) {
    println("GString: " + g)
}

// overloading method with String as parameter
void foo(String s) {
    println("String: " + s)
}

// using generics
class MyClass<T> {
    static void foo(T t) {
        println(t.class.name + ": " + t)
    }
}