8 Jul 2004 11:19
Re: String/number conversion
We don't (today at least) support - on Strings to mean convert to
number if the right hand side happens to be a number. I'm not totally
sure we should - it feels a bit wrong to me (more on this below). I
think we should explicitly covert the expression to a number if thats
what we really mean.
What will work today is
x.toInteger() - 31
which is explicitly saying that you want to consider x being an integer
rather than relying on some magic coercion. We should allow types to be
able to coerce themselves to other types more easily so we could write
this as something like
((int) x) - 31
I think it was Chris who suggested a neater alternative to cast which
avoids parenthesis...
x as int - 31
We can debate on the JSR list as to whether we should magically coerce
Strings into numbers when it looks like users might want that; though I
can't help feel its a slippery slope with strings - since you can
consider characters as being numbers (byte/short/int) and adding or
removing characters to a String (a sequence of characters) might be
more consistent than doing auto-coerce to a numberic value.
e.g.
s = ""
file.eachChar { c | s += c }
might be a not-very-efficient way to add characters to the end of the
string; where c is typically of type Character or char or int,
depending on which Java API you're using.
e.g. java.io.Reader.read() returns a single character using the type
int.
So adding a character read from a Reader might seem the least
surprising thing to do - not coerce it into a number and add the
characters ASCII/UTF integer value to it.
On 8 Jul 2004, at 10:03, Aleksei Valikov wrote:
> Hi.
>
> Sorry for reposting - would be grateful if anyone comments...
> Quite important for me.
>
> I have a problem converting string into number when embedding Groovy
> via BSF.
>
> Here is a part of the testcase:
>
> final BSFManager manager = new BSFManager();
> try
> {
> manager.declareBean("x", new String("1"), String.class);
> final BSFEngine engine = manager.loadScriptingEngine("groovy");
> final Object result = engine.eval("test", 0, 0, "x - 32");
>
> Assert.assertEquals("Wrong value.", new Integer(-31), result);
> }
> catch (BSFException bsfex)
> {
> log.error("Error evaluating the expression.", bsfex);
> Assert.fail("Unexpected exception.");
> }
>
> Test case fails, actual result is "1".
> When I write
>
> manager.declareBean("x", new Integer(1), Integer.class);
>
> test succeeds.
>
> I'd like "1" - 32 to be -31...
>
> Thanks.
>
> Bye.
> /lexi
>
>
James
-------
http://radio.weblogs.com/0112098/
RSS Feed