loading...

Objects as Primitives?

isaacdlyman profile image Isaac Lyman ・2 min read

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:

  1. 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.
  2. 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?
  3. 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.

Posted on by:

isaacdlyman profile

Isaac Lyman

@isaacdlyman

Author of Your First Year in Code (leanpub.com/firstyearincode). Find more of my writing at isaaclyman.com/blog.

Discussion

pic
Editor guide
 

I'm no Haskell expert. But Haskell typeclasses allow you to do that.

To understand the basics, look at typeclasses like C# or Java interfaces, they define one or more methods that your instances should implement.

Eq is a typeclass that allows you to evaluate a value as a boolean. Show is a typeclass that represents a value as a readable String.

Then assuming you have the following data type:

data Animal = Animal String

You can also write the following:

instance Eq Animal where
    (Animal name) == (Animal name) = name == name

instance Show Animal where
    show (Animal name) = name

And that way you can use a data type Animal for equality or as a string. To treat it like a boolean value, there's another typeclass called BoolValue that can do that.

 

A relevant Twitter thread: