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
)
1
  • why not adding a method accepting String? Commented Jan 5, 2022 at 14:44

2 Answers 2

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 + "${''}")
}
Sign up to request clarification or add additional context in comments.

Comments

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)
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.