Var inside a if

Hej,

Is there another way a kind of shortcut to write something like that please ?
I mean this doesn’t compile Try Haxe ! :

class Test {
  static function main() {
    var s	= "5";
    if( ( var v = Std.parseInt( s ) ) != null )
      trace( "ok", v );
    else
      trace( "not ok", v );
  }
}

And this does compile well Try Haxe ! :

class Test {
  static function main() {
    var s	= "5";
    var v	= null;
    if( ( v = Std.parseInt( s ) ) != null )
      trace( "ok", v );
    else
      trace( "not ok", v );
  }
}

I know all in haxe is expression and here it’s not really a big deal, but having many if/else force you to declare the local variable all on the top of all if/else blocks.

Thanks for reading,
Michal

No, unfortunately you can’t declare a var inside condition like this, although this would be useful in some cases.

What you can do however is use switch instead of if, like this:

switch Std.parseInt(s) {
  case null: trace("not ok");
  case v: trace("ok", v);
}

This might look a bit weird if you’re not used to pattern matching, but it’s short and plays nice with scoping.

1 Like

Thanks for your answer Dan,

Yes I also use this kind of pattern matching in other cases, here my example is not very good because i’ve simplified it too much.
But ok, if there is no other way, there isn’t :slight_smile:

if you want v to be only available in the condition, you might want to wrap it in a block, like this:

var s = "5";
{
    var v = Std.parseInt( s );
    if( v != null ) trace( "ok", v );
    else  trace( "not ok", v );
}
1 Like

Thanks Mark for your answer.

Here is maybe a better example what I wanted to shortcut :

class Test {
    static function main() {
        var sval	= "5";
        var val		: Dynamic = sval;
        
        if( sval == "true" || sval == "false" )
            val	= sval == "true";
        else{
            var v	= null;
            if( ( v = Std.parseInt( sval ) ) != null ){
                val	= v;
            }
        }
        trace( val );
    }
}

Just to have less lines to write :stuck_out_tongue: :

class Test {
    static function main() {
        var sval	= "5";
        var val		: Dynamic = sval;
        
        if( sval == "true" || sval == "false" ){
            val	= sval == "true";
        }else if( ( var v = Std.parseInt( sval ) ) != null )
                val	= v;
        }
        trace( val );
    }
}

But it’s yet good that we can do if ( ( v = Std.parseInt( s ) ) != null ) instead of doing :

var v = Std.parseInt( s );
if( v != null )...

Because in cases we need more than one condition test, it can be catched in the same variable, for example :

var v	: Dynamic = null;
if( ( v = Std.parseInt( sval ) ) != null || v == "" + sval ){
	val	= v;
}

I always do exactly this