为什么这个 Groovy 代码试图强制转换?

tin*_*nny 4 groovy

我在“handDetailList.each”行中抛出了一个强制转换异常。我不明白为什么我的代码试图将列表转换为“Hand”类?在我看来,有时 Groovy 会在强制转换方面做一些奇怪的事情......?

private Hand buildHands(List handDetailList) {

        def parsedHand = new Hand()

        parsedHand.setTableName(handDetailList.get(1))


        handDetailList.each {

        }
    }
Run Code Online (Sandbox Code Playgroud)

我得到以下异常(我编辑了异常,第 70 行是“handDetailList.each {”):

Exception in thread "main" org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object <details of the list, omitted> with class 'java.util.ArrayList' to class 'gameMechanics.Hand' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: gameMechanics.Hand(java.lang.String,........


    at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:358)
    at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.castToType(ScriptBytecodeAdapter.java:599)
    at advisor.HistoryParser.buildHands(HistoryParser.groovy:70)
    at advisor.HistoryParser.this$2$buildHands(HistoryParser.groovy)
    at advisor.HistoryParser$this$2$buildHands.callCurrent(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:49)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:133)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
    at advisor.HistoryParser.parse(HistoryParser.groovy:57)
    at advisor.HistoryParser$parse.call(Unknown Source)
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 5

each返回each被调用的列表。

您已经说过该函数返回一个类型Hand为的对象,并且当 Groovy 自动返回方法中的最后一条语句时,它正在尝试将列表转换为Hand...

你想返回什么?该parsedHand变量?

也许尝试:

private Hand buildHands(List handDetailList) {
    def parsedHand = new Hand()
    parsedHand.setTableName(handDetailList.get(1))
    handDetailList.each {
    }
    parsedHand
}
Run Code Online (Sandbox Code Playgroud)

如果是这样的话。