gpt4 book ai didi

groovy - 链接为零的安全算子

转载 作者:行者123 更新时间:2023-12-04 16:24:17 25 4
gpt4 key购买 nike

我的项目具有如下代码:

params.stringValue?.trim().replaceAll('aa', 'a')

我们期望如果 params.stringValue为null,则不会同时调用 trim()replaceAll()

但是,我们在这一行上得到了一个 NullPointerException,说不能在空对象上调用 replaceAll()

我们必须将代码更改为如下形式:
params.stringValue?.trim()?.replaceAll('aa', 'a')

为什么上面的第一个代码段不起作用?这是Groovy中的bug,它在遇到空值一次后会继续对表达式求值吗?

最佳答案

实际上,这就是Groovy的工作方式,并且咬住了others:

println book?.author?.firstName?.trim().concat(" is great.")

...

Looking at this line of code, I thought for sure I was safe from any sneaky NullPointerException. If book, author or firstName are null I'll simply end up printing null and not have to worry about the concat() method. After all, if the trim() method succeeds, there's no sense in guarding it's result for null. And that's where I was wrong.


至少有 this discussion可以更改它:

a?.b.c // Do you see the error? ;)

I will get a NullPointerException. I mean, if you use the null-safe ?. operator in a chained expression,you have to use in all properties because if you forget to put in somewhere, you will get an error too. It willbe nice if Groovy could detect the ?. operator in an expression, and it injects it in the other properties ifit sees the operator is missing. So, if you would type this

a?.b?.e.f?.g // I forget to put the ?. .n the "f" propertya?.b.e.f.g

Groovy could fix it with a real null-safe expression like this:

a?.b?.e?.f?.g

关于groovy - 链接为零的安全算子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30803287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com