Why Groovy Enum Constructors Fail with Char Literals and How to Fix Them

The article explains a Groovy runtime initialization error caused by the language treating both double‑quoted and single‑quoted literals as Strings rather than chars, leading to a mismatched enum constructor, and provides a corrected enum definition with explicit char casting to resolve the issue.

FunTester
FunTester
FunTester
Why Groovy Enum Constructors Fail with Char Literals and How to Fix Them

Problem Code

package com.fun.ztest.groovy

import com.fun.moco.MocoServer

class MocoDemo extends MocoServer {
    public static void main(String[] args) {
        println FunTester.FUN
    }

    static enum FunTester {
        FUN('3'), TESTER('2')
        char name
        FunTester(char name) {
            this.name = name
        }
    }
}

Running this class produces an ExceptionInInitializerError with the message

Could not find matching constructor for: com.fun.ztest.groovy.MocoDemo$FunTester(String, Integer, String)

, indicating that Groovy could not locate a suitable constructor for the enum constants.

Root Cause Analysis

Groovy does not distinguish between double quotes ( "") and single quotes ( '') when they are used as character literals; both are interpreted as String objects. The enum constructor expects a char, but the literals are passed as String, causing the initialization failure.

The following snippet demonstrates that both "3" and '3' are treated as String types:

public static void main(String[] args) {
    println "3".class.getName()
    println '3'.class.getName()
}

Console output:

java.lang.String
java.lang.String

Fix

Explicitly cast the literals to char when defining the enum constants. The corrected enum definition looks like this:

class MocoDemo extends MocoServer {
    public static void main(String[] args) {
        println FunTester.FUN
    }

    static enum FunTester {
        FUN((char)'3'), TESTER((char)'2')
        char name
        FunTester(char name) {
            this.name = name
        }
    }
}

Running the corrected code produces the expected output without errors:

INFO-> 当前用户:fv,IP:10.60.131.54,工作目录:/Users/fv/Documents/workspace/fun/,系统编码格式:UTF-8,系统Mac OS X版本:10.16
FUN
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaprogrammingenumGroovybug fixConstructor
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.