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.

Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: