【发布时间】:2018-04-13 20:51:53
【问题描述】:
我知道这对我来说可能很不合时宜,但我需要能够在数组中存储一个空字符串。根据我的发现,它看起来像这样:string = '' 最终与string = null 相同。
这是真的还是我错过了什么?
如果是真的,我如何在groovy中初始化一个字符串并使其为空?
【问题讨论】:
-
这不是真的
标签: groovy
我知道这对我来说可能很不合时宜,但我需要能够在数组中存储一个空字符串。根据我的发现,它看起来像这样:string = '' 最终与string = null 相同。
这是真的还是我错过了什么?
如果是真的,我如何在groovy中初始化一个字符串并使其为空?
【问题讨论】:
标签: groovy
Groovy 不认为 '' 等于 null。
'' == null
===> false
也许您是在布尔表达式的上下文中读到的,其中两者是等价的(if(null) 和 if('') 都评估为 false)。
你可以用通常的方式声明一个字符串:
String str = ''
def str = ''
【讨论】:
您可以向数组添加一个空字符串,您是否尝试根据使用the groovy truth 的数组的值执行一些逻辑?
def myArr = new String[3]
myArr[0] = 'hello'
myArr[1] = ''
myArr[2] = null
myArr.each{ println it }
// prints
hello
null
// whereas the following...
myArr.each{ if (it) println it }
// prints
hello
// and nothing else
【讨论】: