#18 Auto-convert

brian Tue 27 Dec 2005

Java (and C# I'm pretty sure) have a couple weird edge cases where they auto-convert values. They automatically allow casts to more precise numeric types (like you can use an int in place of an expression that requires a long). Plus string concat is allowed to start with an expr which isn't a string:

long x = 4;
String = x + "x";

I'm thinking that Fan shouldn't support these two edge cases because they don't really fit a clean OO model. In the auto-cast case Int is not a Real so it really isn't a true cast and becomes a special case (which likely would alloc a new instance). Furthermore since there is just Int and Real (and not a zillion numeric types), the whole need for this feature largely goes away. If something requires a Real, then you pass a Real - end of story.

The string case is another weird case, because Int or Real don't support the plus operator that takes a string argument:

Int x;
x + " foo" -> x.plus(" foo") -> Int.plus(Str) // no can do

However as long as the lhs expression is a Str, then we cleanly map to Str.plus(Obj) which takes any object. In general I don't think that is a big deal and keeps things much cleaner. Furthmore, string interpolation largely makes this is a non issue anyway since best practice would be to write the above as:

"#{x} foo"

Let me know if you disagree.

andy Wed 28 Dec 2005

That's probably ok - though its nice to be able to make a string out of anything - though I guess it depends on what I can put in #{} - what if I need a method:

foo := someObj.calc() + " foobars"

Here I don't want to have to create a variable just to create this string - don't have a strong preference on how its done as long as I can do it.

brian Wed 28 Dec 2005

String interpolation lets you use any expression. Ruby let's you shortcut instance variable names to leave off the {}. Some examples in Fan assuming we use #{} as our syntax:

x := 5
"var #x"
"in hex = #{x.toHex}"
"plus 5 = #{x + 5}"

Your example could be written:

foo := "#{someObj.calc} foobars"
foo := "" + someObj.calc + " foobars"
foo := someObj.calc.toStr + " foobars"

andy Wed 28 Dec 2005

Sounds fine to me.

Login or Signup to reply.