Tag Archives: contravariance

Towards real OOP — contravariance

I wonder if the boom of dynamic languages is not the effect of the incorrectly stated limits of statically typed languages like Java or C#.

It is pretty basic, but anyway:

interface Contract
  def compute(input String) Object;
end

Interface is a contract indeed — in this example we say that if you refine compute you should be able to tackle with String in input and Object in output. But let’s say we write:

class Worker refines Contract
  refines def compute(input Object) Int •••
end

Did we just violate the contract of the interface? No — we were supposed to produce Object, and Int is Object. We were supposed to cope with String in the input and we do even better — we handle all possible types (nothing is higher in type hierarchy than Object). We fulfilled the contract and added a bonus for those who use Worker type directly.

Well, I cannot speak for other languages, but Skila supports both sides of the refinement.

Tagged , ,

First step into covariant world

It is interesting how given concepts of programming languages made their way into the mainstream — I was able to observe how functions from “uhm, do we really need them?” perspective became first class citizens (“what, you cannot pass a function to a function?”).

The next thing on my watch list is covariance and contravariance — they were finally introduced in C#, but sadly, only partially.

Since I am working back and forth now on improving support of functions in Skila it was a hard to miss an opportunity to finally make this happen:

struct Foo 
  def virtual get() Foo = new Foo();
end

struct Bar : Foo
  def override get() Bar = new Bar();
end

You don’t have to mark those methods in any special way, compiler knows you are overriding the method, so you can return a derived type in a derived class. That’s it — done!

Adding this/self (self reference to current type instance) and THIS/SELF (per analogy, current type) is right behind the corner. In a way it will be a return to one of the COOL features, yet with more flexibility.

Tagged , , , , , ,