#987 Separating declaration from initliazation for non-nullable variables

tactics Fri 19 Feb 2010

Something that's bitten me a few times is when you try to declare a variable early on in a method with the intention to initialize it further down (of course, before any possible uses).

As a simple example, this code:

class Main
{
  static Void main()
  {
    Str x
    x = "hello"
    echo(x)
  }
}

Produces this error message:

C:\Documents and Settings\Michael\Desktop\Main.fan(5,5): 'null' is not assignable to 'sys::Str'
ERROR: cannot compile script

There is no need for this, though. The variable x is given its value at the 2nd line of the method, and it's given its value before its first use on the 3rd line.

Would it be possible to change the semantics so that the assignment of a non-nullable variable can be deferred?

MoOm Fri 19 Feb 2010

It would indeed be useful when the value depends on a condition. For example:

Str x
if (cond)
{
  ...  //Code that compute the value of x
  x := res1
}
else
{
  ...  //Code that compute the value of x
  x := res2
}

Currently, this doesn't compile. Sometimes, the ternary operator can be used to solve this problem, but that's not always possible.

DanielFath Fri 19 Feb 2010

A question

class Main
{
  static Void main()
  {
    Str x
    echo(x)
  }
}

Would throw an error, right? Because, first thing that occurs to me in such case is assign a default value to x.

tactics Fri 19 Feb 2010

Would throw an error, right? Because, first thing that occurs to me in such case s assign a default value to x.

Correct. The behavior is just like Java when a variable is used before initialization. All code paths must assign it a value before any code path may reference it.

brian Fri 19 Feb 2010

I haven't implemented definite assignment analysis in the compiler yet.

Once I do that we can fix these sort of things (as well as warnings for unused variables).

In the meantime, what I did was say that variable with an default value is assumed to initialize to null (or false/0 in case of value types).

In the meantime the two workarounds are:

  • give a default dummy value like x := ""
  • stick "?" on the type to make it nullable
  • use ":?" operator for one line initialization if you can

Login or Signup to reply.