#2056 Inicialization of non-nullable fields

bedla Tue 13 Nov 2012

Hi, I have class with not-null field and have to initialize it in constructor. But when I refactor the initialization into private method compiler complains about not initialized fields. Is it even possible to inicialize fields like that? Or could you add it to the language? :-) Thanks Ivos

class NonNullFields
{
    Str field1

    new make()
    {
        privateMethod
    }

    private Void privateMethod()
    {
        field1 = ""
    }

    static Void main(Str[] args)
    {
        NonNullFields()
    }
}

Output:

  Compile [fantomtest]
    FindSourceFiles [2 files]
C:\Users\ivo.smid\IdeaProjects\fantom-test\fan\NonNullFields.fan(5,5): Non-nullable field 'field1' must be assigned in constructor 'make'
C:\Users\ivo.smid\IdeaProjects\fantom-test\fan\NonNullFields.fan(17,9): Not a statement
BUILD FAILED [29ms]!<pre

brian Tue 13 Nov 2012

Is it even possible to inicialize fields like that?

No, it works similar to Java final fields - they have to be actually set in the constructor. Couple work arounds:

  • if your ctor takes it-block, the check is delayed until runtime
  • assign dummy value in your field definition

bedla Tue 13 Nov 2012

Ok, thx :-)

Login or Signup to reply.