Reputation: 45
The following code returns an exception:
String x = "12"
double y = x
However this one doesn't:
String x = "12"
double y = x as double
In my application, I have a string x, and I would like to try automatically to cast it with the 'as' keyword to the class of the variable I am affecting it to, though I don't know the class of y
in advance. Is that possible without some witchcraft, such as using as y.class
or something?
String x = "12"
y = x
The above code returns an error if y happens not to be a string (such as a double), though I'd like it to try to cast x to the type of y before failing.
Upvotes: 1
Views: 2070
Reputation: 9885
The expression x as double
is the same as the method call x.asType(Double)
. So you can use this simple pagan spell:
String x = "12"
double y
y = x.asType(y.class)
Upvotes: 4
Reputation: 14529
You can test it before casting:
groovy:000> s="x12"
===> x12
groovy:000> s.isNumber() ? s.toDouble() : null
===> null
groovy:000> s = "12"
===> 12
groovy:000> s.isNumber() ? s.toDouble() : null
===> 12.0
Upvotes: 0