2016-03-15 21 views
9

首先,我知道問題'Groovy String to int',它是響應。我是Groovy語言的新手,現在正在玩一些基礎知識。最直接的方式將字符串轉換爲int似乎是:如何將字符串轉換爲Groovy中的int

int value = "99".toInteger() 

或:

int value = Integer.parseInt("99") 

這些都工作,但評論這些問題的答案讓我困惑。正如groovy文檔中所述,第一種方法

String.toInteger()
已棄用。我還假設

Integer.parseInt()
利用核心Java功能。

所以我的問題是:有沒有任何法律,純粹groovy方式來執行這樣一個簡單的任務,如轉換字符串爲int?

+2

'String.toInteger'不會被棄用,這只是轉移到'CharSequence'(一個字符串是一個CharSequence) –

+0

謝謝@tim_yates,但根據http://docs.groovy-lang.org/latest/html/gapi/org/codehaus/groovy/runtime/DefaultGroovyMethods.html# toInteger(java.lang.CharSequence)我認爲CharSequence版本也被棄用。然而,我現在看到java.lang.Number的版本沒有被棄用,但現在我清楚地知道當我的String成爲一個數字時... – koto

+0

是的,這是內部文檔。該方法已被棄用,因爲它被轉移到了不同​​類的接口文檔在這裏:http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#toInteger( ) –

回答

19

我可能是錯的,但我認爲最Grooviest的方式將使用安全鑄造"123" as int

真的,你有很多方式,行爲稍有不同,都是正確的。

"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而不是異常,請使用您鏈接的答案中的recipe。

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

我接受了答案,但我無法投票,因爲我沒有足夠的代表... – koto

+0

現在我可以投票:) – koto

+1

@koto祝賀您在StackOverflow上成功開始! =) – Seagull

0

如果你想轉換一個字符串,它是一個數學表達式,不只是一個單一的數字,嘗試groovy.lang.Script.evaluate(String expression)

print evaluate("1+1"); // note that evalute can throw CompilationFailedException 
+2

這似乎有點偏離主題,因爲OP詢問了簡單的方法將String轉換爲int。 任何類型的評估都會導致很多安全問題。 此外,不推薦使用Script#evaluate來執行您的建議,但[groovy.util.Eval](http://docs.groovy-lang.org/latest/html/api/groovy/util/Eval。 HTML)是。 – Seagull