Monthly Archives: February 2018

Extending generic types with traits

I am pretty happy I managed to add the feature I was not able to while working on previous Skila — traits. Initially I thought about them as conditional methods:

class Greeter<T>
{
  void hello(T &t) where T : ISay
  {
    t.say();
  }
}

But when reading “Programming Rust” I noticed that syntax for Rust type implementations and this gave me the idea of decoupling those “conditional methods” from the main type:

class Greeter<T>
{
}

trait Greeter<T>
  where T : ISay
{
  void hello(T &t) 
  {
    t.say();
  }
}

It looks very much like extension method however you can spice it with inheritance:

class Greeter<T>
{
}

trait Greeter<T> : ISay
  where T : ISay
{
  void hello(T &t) 
  {
    t.say();
  }
  // traits support polymorphism
  override void say()
  {
    println("just saying");
  }
}

Depending which type you pass when constructing Greeter it will inherit from ISay or not.

At this point there is a little zoo in Skila with similar features — protocols and interfaces, traits and extensions (upcoming) — and I hope some of them will be merged. Simplicity matters.

Advertisement
Tagged , ,