【问题标题】:Is it possible to have a string in groovy by empty and not null?是否有可能在 groovy 中有一个空字符串而不是空字符串?
【发布时间】:2018-04-13 20:51:53
【问题描述】:

我知道这对我来说可能很不合时宜,但我需要能够在数组中存储一个空字符串。根据我的发现,它看起来像这样:string = '' 最终与string = null 相同。

这是真的还是我错过了什么?

如果是真的,我如何在groovy中初始化一个字符串并使其为空?

【问题讨论】:

  • 这不是真的

标签: groovy


【解决方案1】:

Groovy 不认为 '' 等于 null

'' == null
===> false

也许您是在布尔表达式的上下文中读到的,其中两者是等价的(if(null)if('') 都评估为 false)。

你可以用通常的方式声明一个字符串:

String str = ''
def str = ''

【讨论】:

    【解决方案2】:

    您可以向数组添加一个空字符串,您是否尝试根据使用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
    

    【讨论】:

      猜你喜欢
      • 2014-06-23
      • 2013-07-01
      • 2012-02-28
      • 2023-02-15
      • 2010-12-16
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      相关资源
      最近更新 更多