加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

@Immutable如何在groovy中工作?

发布时间:2020-12-14 16:30:01 所属栏目:大数据 来源:网络整理
导读:当我在groovy控制台中执行下面的代码时,我得到一个groovy.lang.ReadOnlyPropertyException.这是预期的,因为属性x不可能改变(因为ClassA是不可变的). import groovy.transform.Immutable@Immutable class ClassA { int x}def a = new ClassA(x: 5);a.x = 1 但
当我在groovy控制台中执行下面的代码时,我得到一个groovy.lang.ReadOnlyPropertyException.这是预期的,因为属性x不可能改变(因为ClassA是不可变的).

import groovy.transform.Immutable
@Immutable class ClassA {
    int x
}

def a = new ClassA(x: 5);
a.x = 1

但是如果将x的变量的访问修饰符更改为private,那么我可以在groovy控制台中执行它:

import groovy.transform.Immutable
@Immutable class ClassA {
    private int x
}

def a = new ClassA(x: 5);
a.x = 1
println(a.x)

为什么是这样?为什么添加的私有访问修饰符使ClassA可变?

解决方法

docs对此有明确的立场.他们总是谈论“财产”.也有exerpts指出,“滚动你自己”不被视为“状态”:

You don’t have to follow Groovy’s normal property conventions,e.g. you can create an explicit private field and then you can write explicit get and set methods. Such an approach,isn’t currently prohibited (to give you some wiggle room to get around these conventions) but any fields created in this way are deemed not to be part of the significant state of the object and aren’t factored into the equals or hashCode methods.

这是一个简单的指标,即为这些类创建toString.例如.:

@groovy.transform.Immutable
class A {
    private int a
}

@groovy.transform.Immutable
class B {
    int b
}

a=new A()
a.a = 42
println a
b=new B()
// b.b = 42
println b

将打印:

A()
B(0)

显示,A. @ a不属于不可变性的“计算”(“重要状态”).并且您可以在groovy中访问私有变量,上面的代码工作得很好.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读