openlang

Groovy call to Java encode() with null = ambiguous method, but Java side is fine

I moved my CSV export loop from Java to Groovy and now the job dies on the row with missing nickname. Java FieldEncoder has three encode overloads (String, Number, Collection), and null should become token NULL. In old Java code encoder.encode(user.getNickname()) works fine with null.

Groovy side:

def cells = COLUMNS.collect { col -> encoder.encode(row[col]) }

Row 3 has no nickname key. First line of the error say ambiguous method overloading, and the argument list is [null]. I print row[col] and it show null, so map looks normal. I also changed nullToken, no difference.

Is Groovy 4.0.22 returning something strange for missing key, or not supporting the null token option? Why Java handle null here but Groovy cannot?

Thanks for any help.

The conversation continues 3

Follow the reasoning
  1. Permalink

    Java picks the overload at compile time from the static type, String here, so null is fine. Groovy dispatches at runtime, and a bare null matches String, Number and Collection equally. Cast it: encoder.encode((String) row[col]). Or add an encode(Object) overload.

  2. Permalink

    imke is right. Groovy isn't returning anything strange, null is just null at runtime. Cast it, or use row[col] as String. Hit the same thing in a Gradle script calling my Java helper. Annoying. I'd add encode(Object) and handle null there, so the call site stays clean.

    encoder.encode(row[col] as String)
  3. Permalink

    Thanks both, the cast works. But as String on a Number column, does it convert the value to text?

Other sides of the same question

  1. Is a read-only List<Int> a snapshot?

    List<Int> is a read-only view, not a snapshot. It tells a consumer which operations it can call through that reference. It pr…

    Replies 4Latest activity kotlin
  2. Private union cases, smart constructor, and still `Colors []` after remove?

    Hello all, I have a small swatch editor with a three-case palette union. A fresh edit is NotEntered, a deliberate clear is Em…

    Replies 1Latest activity fsharphaskell
  3. Units of measure as cheap ids

    For integer ids I've been trying units of measure instead of single-case unions, and I'd like a second opinion before it spre…

    Replies 1Latest activity fsharp