#1910 Inheritance Question

yliu Thu 14 Jun 2012

This is probably gonna be super easy to answer but... consider:

const class Foo
{
  const Str? name

  new make(|This| f){f(this)}

  Foo setName(Str newName)
  {
    return ???(newName)
  }
}

const class Bar : Foo
{
  new make(|This| f):super(f){}
}

Now if I want to call Bar.setName(Str) I want it to return an object back of class Bar, not of class Foo. Need some help filling in the blanks.

Yuri Strot Thu 14 Jun 2012

You can use This return type:

const class Foo
{
  const Str? name

  new make(|This| f){f(this)}

  virtual This setName(Str newName)
  {
    Foo { it.name = newName }
  }
}

const class Bar : Foo
{
  new make(|This| f):super(f){}

  override This setName(Str newName)
  {
    Bar { it.name = newName }
  }
}

yliu Thu 14 Jun 2012

So there's no way of doing this without having a virtual method and overriding it for every subclass? Hmm I might resort to a different approach.

SlimerDude Thu 14 Jun 2012

The only other way would be to use reflection.

brian Thu 14 Jun 2012

Is your problem a static typing issue, or just how to create instances of the proper class?

If it is creating instances, then just use typeof.make. Since your constructor takes an it-block, it depends on what you want there. But you can use reflection to build an it-block too using Field.makeSetFunc.

yliu Thu 14 Jun 2012

@Brian I think thats exactly what I was looking for. So it would be something like this?

const class Foo
{
  const Str? name

  new make(|This| f){f(this)}

  Foo setName(Str newName)
  {
    f := Field.makeSetFunc(Foo#name:newName)
    return this.typeof.make([f])
  }
}

const class Bar : Foo
{
  new make(|This| f):super(f){}
}

brian Thu 14 Jun 2012

Basic idea, the makeSetFunc takes a function:

Field.makeSetFunc( [#name: "someName"])

Login or Signup to reply.