string - 将空字符串转换为 null 的 Groovy 方法

标签 string groovy

我想要一个 Groovy 函数,如果传入的值是空字符串,则该函数将返回 null,否则返回该字符串。这就是我能想到的..

def emptyStringNullConverter(a) {
    return a?.toString()?.length() == 0 ? null : a
}

但是有没有更好的方法来做到这一点?

最佳答案

你可以这样做:

def emptyStringNullConverter(a) {
    a ?: null
}

关于string - 将空字符串转换为 null 的 Groovy 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61545204/

相关文章:

Grails 缓存插件 : Cacheable key using only two of three params

java - Objectify 无法将大于 500 个字符的字符串自动转换为 @Embed 集合中的文本

mysql - SQL 在不同的字节中拆分 hexastring

java - 在java中存储字符串值

java - 如何去掉字符串中的多个空格并保留一个

grails - 在没有请求的情况下使用GroovyPagesTemplateEngine?

Java将所有 float 格式化为字符串

grails - 我可以将参数从 Controller 传递到服务类吗

elasticsearch - Groovy脚本 Elasticsearch 的日期差异

groovy - 使用 'it'进行Groovy嵌套闭包