I've been mulling over a weird idea for a while now and I want to pitch it for discussion. I call it "objects as primitives", although you could call it "strictly-typed loose typing" if you enjoy a good oxymoron.
The idea is this: a strictly-typed language (say, C#) would have a couple of built-in interfaces that allow an object to be evaluated as a primitive in certain contexts. The best way to demonstrate this is a code sample:
class Animal : IAsString, IAsBoolean {
private string name;
public Animal(string name) {
this.name = name;
}
public string AsString() {
return this.name;
}
public bool AsBoolean() {
return !String.IsNullOrEmpty(this.name);
}
}
(yes, I know strings are not technically primitives. I find that very annoying.)
Then in another part of the code:
public bool IsCat(Animal animal) {
return animal && animal == "cat";
}
So in animal && animal == "cat"
, the compiler would understand that the first animal
is syntax sugar for animal.AsBoolean()
and the second animal
is syntax sugar for animal.AsString()
. And presumably there would be other "IAsPrimitive" interfaces for byte
, char
, and number types.
So here are my questions:
- Do any languages have this? I know C# allows you to overload operators, so the
animal == "cat"
part is possible, although not in the way I've described. - Is this even a good idea? Does it introduce unwanted ambiguity, or is it just a piece of syntax sugar we would learn to recognize?
- What about doing this in a loosely-typed language like JavaScript? Would it be an advantage to be able to describe the kind of typecasting we want the interpreter to do, or would it just create a ton of gotchas for people who really understand JavaScript?
Let me know what you think.