Typedef with setters

Hi I’m trying to make a typedef that has setters in them. I got about this far:

typedef PosSetter = {
	var x:Float;
}
  
function setX(s:PosSetter) {
  s.x += 5;
}


class Player {
	public var x(default, set):Float = 0;

	function set_x(x:Float):Float {
		this.x = x;
		return x;
	}

	public function new() {}
}

class Player2 {
	public var x:Float; // This works, but I need it to work with setters like for `Player`
	public function new() {}
}


class Test {
  static function main() {
    setX(new Player()); // Errors here 
  }
}

/*

 22 |     setX(new Player()); // Errors here 
    |          ^^^^^^^^^^^^
    | Player should be PosSetter
    | Inconsistent setter for field x : set should be default
    | For function argument 's'
*/

Here is the playground link: Try Haxe!

How would I get typedef to accept classes that have setters instead of values like I have for Player here?

You need to change your typedef to say that x has a setter:

typedef PosSetter = {
	var x(default, set):Float;
}

which will work for Player but not Player2.

1 Like

Thanks! With your help I made a version that would work with the cases that had the normal variables as well, by overloading:

typedef PosX = {
	var x(default, set):Float;
}
  
typedef PosSetterX = {
	var x:Float;
}

  
overload extern inline function setX(s:PosSetterX) {
  s.x += 5;
}

overload extern inline function setX(s:PosX) {
  s.x += 5;
}

setX(new Player());
setX(new Player2());