views:

252

answers:

2

I have a class like this..

public class Doc {
  public function Doc():void {}

  public var myVar:Boolean;
}

How can I know if the value hold by myVar is the default false, or someone has assigned false to it ?!? Isn't there an undefined state? How can I achieve such a thing?

+4  A: 

Make myVar a property and use another variable to check if it's been set explicitly.

public class Doc 
{
  public function Doc():void {}

  private var _myVar:Boolean;
  private var myVarSetExplicitly:Boolean = false;
  public function get myVar():Boolean
  {
    return _myVar;
  }
  public function set myVar(value:Boolean):void
  {
    myVarSetExplicitly = true;
    _myVar = value;
  }
}
Amarghosh
the flex framework itself uses examples of this very concept to find out if a value has been changed. This is the best answer. You should accept it as the right answer ;)
Ryan Guill
A: 

You can't with a boolean, it defaults to false and false === false.

You'd could not strictly type the variable and then use a getter and setter to protect the type

public class Doc {
  private var _myVar;

  public function set myVar(value:Boolean){
    _myVar = value;
  }

  public function get myVar(){
    return _myVar;
  }
}

Now, when its not set myVar should === null, and you should only be able to set it to a boolean after that.

But it feels a bit hacky, and I wonder why you need to tell the difference.

Simon
I need this because the object gets created, populated (if partly) and then sent as XML. But if a var hasn't been set I don't want it to be sent at all in the xml.
luca
no this is a mess!! Can you suggest me something different to achieve my goal? point is some fields can be NULL in the database and they are only if I don't send them.. (backend is rails)
luca
How is this a mess? Getters and setters are pretty standard and would allow you do do what you want... the Doc.myVar would default to null and then can only be set to a boolean, which to me sounds like exactly what you're asking for?
Simon
whould I ignore the compiler warnings? it says no return type given for the getter and no type given to _myVar..I don't like warnings they're ugly =)
luca
As I mentioned in my answer, we had to remove the strict typing to be able to do what you wanted, so I'm afraid you'll have to ignore them.
Simon
Be aware that you lose some performance by not using the strict typing.
Glenn
You can get rid of compiler warnings by typing as Object (which will allow you to support null) or * (which supports everything Object does, plus undefined).
joshtynjala
Avoid not typing variables at all costs. You lose all compiler help and it has negative performance costs. Amarghosh's answer is what you should do.
Ryan Guill