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 held by myVar is default false, or someone has assigned false to it ?!? Isn't there an undefined state? How can I achieve such a thing?

2 Answers 2

5

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;
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

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 ;)
0

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.

8 Comments

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.
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)
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?
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 =)
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.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.