创建带有“with”块的实例会导致类型问题

Creation of an instance with `with` block causes a type issue

提问人:Aymen Turki 提问时间:1/30/2023 最后编辑:Aymen Turki 更新时间:1/30/2023 访问量:64

问:

我正在使用 Groovy 创建一个我在 ReadyApi 中使用的包。

在 Groovy 脚本测试步骤中,我执行以下操作:

class B  {
    String value
    boolean isSomething
}

class A {
    String name
    B propB

    public A() {
        this.name = "Maydan"
    }
}

def x = (A) new A().with  { propB = new B(value: "Abc", isSomething: true) }

我收到以下错误:

org.codehaus.groovy.runtime.typehandling.GroovyCastException:无法将类为“B”的对象“B@6c218cea”转换为类“A” 第 15 行错误

有人知道为什么吗?这对我来说没有任何意义。

亲切问候。

PS:我想创建一个类 A 的实例(通过使用其无参数构造函数)并在单个语句中设置其字段 propB

Groovy 强制转换 闭包 with-statement object-initializers

评论


答:

1赞 Andrej Istomin 1/30/2023 #1

您需要从闭包中返回对象。你可以这样做:A.with

def x = (A) new A().with  { propB = new B(value: "Abc", isSomething: true); return it}

但就我个人而言,这看起来有点奇怪。我会这样做:

def x = new A(propB: new B(value: "Abc", isSomething: true))

效果相同,但更紧凑,更易读。它不需要更改你的和定义,这个“地图构造函数”在Groovy中开箱即用,它将调用你的无参数构造函数,然后分配必要的字段(在你的情况下)。ABpropB

评论

0赞 Aymen Turki 1/30/2023
谢谢!我对 C# 对象初始值设定项的了解有偏见(因为我通常是 C# 开发人员)。(顺便说一句,第二个解决方案不符合我的需求,因为我想调用 A 中定义的无参数构造函数)
1赞 Andrej Istomin 1/30/2023
@AymenTurki我已经更新了我的答案,您无需重新定义 A 或 B,它将为您工作,无需您想要的任何更改。这是 Groovy 语法糖。