如何在Groovy中以正确的方式将String转换为int [英] How to convert String to int in Groovy the right way

查看:119
本文介绍了如何在Groovy中以正确的方式将String转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道问题'将字符串转换为int ',它是回应.我是Groovy语言的新手,目前正在学习一些基础知识.将String转换为int的最直接方法似乎是:

First of all, I am aware of question 'Groovy String to int' and it's responses. I am a newbe to Groovy language and right now playing around some basics. The most straightforward ways to convert String to int seem to be:

int value = "99".toInteger()

或:

int value = Integer.parseInt("99")

这两种方法都有效,但是对这些答案的评论使我感到困惑.如groovy文档中所述,不赞成使用第一个方法

These both work, but comments to these answers got me confused. The first method

String.toInteger()

.我还认为

Integer.parseInt()

使用了Java的核心功能.

makes use of the core Java feature.

所以我的问题是:是否有任何合法,纯常规的方法来执行将String转换为int这样简单的任务?

So my question is: is there any legal, pure groovy way to perform such a simple task as converting String to an int?

推荐答案

我可能是错的,但我认为大多数Grooviest 方式将使用安全的"123"转换为int .

I might be wrong, but I think most Grooviest way would be using a safe cast "123" as int.

真的,您有很多方式的行为略有不同,而且都是正确的.

Really you have a lot of ways with slightly different behaviour, and all are correct.

"100" as Integer // can throw NumberFormatException
"100" as int // throws error when string is null. can throw NumberFormatException
"10".toInteger() // can throw NumberFormatException and NullPointerException
Integer.parseInt("10") // can throw NumberFormatException (for null too)

如果要获取null而不是异常,请使用已链接答案的配方.

If you want to get null instead of exception, use recipe from answer you have linked.

def toIntOrNull = { it?.isInteger() ? it.toInteger() : null }
assert 100 == toIntOrNull("100")
assert null == toIntOrNull(null)
assert null == toIntOrNull("abcd")

这篇关于如何在Groovy中以正确的方式将String转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆