16 Jul 2004 09:01
Re: Conversion of types
On 14 Jul 2004, at 22:50, Dion Almaer wrote:
> Hi -
>
> What do you guys think about smart conversion of types in situations?
>
> E.g. compare a Perl script to a Groovy one:
>
> Perl
>
> ---------------------------------------------------
> #!/usr/local/bin/perl
>
> my $amount = "1";
>
> if ($amount < 2) {
> print "Amount is less than two\n";
> }
> ---------------------------------------------------
>
> (this will print 'Amount is less than two')
>
> ---------------------------------------------------
> amount = "1";
>
> if (amount < 2) {
> println "Amount is less than two";
> }
> ---------------------------------------------------
>
> (this won't work)
>
> What are peoples thoughts on this?
I'm a little worried about 'clever' auto-type coercion, especially when
using strings and numbers. Often Java methods return an int/Integer
meaning a 'character' and so comparisons/operations are meant to coerce
an int into a Character.
e.g. many of the stream methods return type 'int' for a character.
String text = "f"
Reader r = ...
int ch = reader.read()
if (text == ch) {
...
}
In the above we are coercing things into a Character and performing
comparisons.
This would seem to conflict with treating ch as a number.
So to avoid confusion I think I prefer explicit coercion of strings to
numbers. Also remember, numbers as a string are frequently
locale-dependent - so we often need to know which locale to use.
e.g.
// use JVM default
"1,200".toNumber()
// use specific locale
"1,200".toNumber(myLocale)
James
-------
http://radio.weblogs.com/0112098/
RSS Feed