i was testing with class instantiation and everything worked until i tried to implement
public var total = add();
and came to an error regarding the call to add() function :
Cannot access this or other member field in variable initialization
according to my understanding of visibility, private function add() and variables a and b should be accessible to the call in the same class, so im kinda confused. any help is appreciated!
class Main{
static function main() {
var ans = new X(5,6);
trace(ans.total);
}
}
class X{
var a:Int;
var b:Int;
public var total = add();
public function new(a,b)
{
this.a=a;
this.b=b;
}
function add()
{
return a+b;
}
}
Well, there’s nothing more to tell
It’s not about visibility. Haxe just doesn’t allow to use any instance fields or this in init expressions of instance vars.
Instead of
public var total = add();
public function new(a,b)
{
this.a=a;
this.b=b;
}
you have to do
public var total = add();
public function new(a,b)
{
this.a=a;
this.b=b;
this.total = add();
}
class Test{
static function main() {
var ans = new X(5,6);
trace(ans.total);
}
}
class X{
var a: Int;
var b: Int;
public var total( get, never ): Int;
public function get_total(){
return a+b;
}
public function new(a_,b_){
a=a_;
b=b_;
}
}