#487 initialize const field in superclass - how to?

KevinKelley Mon 23 Mar 2009

Quick question, take this example:

class Text {
  const Bool wrap := false
  ...
class MyText : Text {
  new make() {
    wrap = true

gives error, Can't set const field.

But

class MyText {
  Text mytext := Text {
    wrap = true

works. Probably to do with the with-block discussion going on?

brian Mon 23 Mar 2009

No question about it - that is related to the it-block discussion.

Today you can set a const instance field:

  1. in your constructor (not subclass)
  2. in with-block after constructor

With new it-block proposal you can set a const field:

  1. in your constructor (not subclass)
  2. in it-block run in the constructor

I am not sure what that looks like with new proposal, but probably something like this:

class Text
{
  const Bool wrap := false
  new make(|This| f) { f(this) }
}

class MyText : Text
{
  new make(|This| f) : super(|This it| { it.wrap=true; f(it)}) {}
}

Where the function you pass to your super constructor sets the const fields, then invokes the function passed to yourself.

That is an interesting use case to consider.

andy Thu 25 Apr 2013

This has bitten me a few times now - did we ever decide how to make this work?

katox Thu 25 Apr 2013

The best thing would be if it worked with a normal it-block. Right now const fields can't be set without makeSetFunc which is rather counter-intuitive and confusing for newcomers.

Login or Signup to reply.