Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Override the default toString function of an enum #10091

Closed
kevinresol opened this issue Jan 28, 2021 · 3 comments
Closed

Override the default toString function of an enum #10091

kevinresol opened this issue Jan 28, 2021 · 3 comments

Comments

@kevinresol
Copy link
Contributor

Currently there seems no way to override the default toString behaviour of enum that would work with Std.string()

class Main {
	static function main() {
		final e = Integer(16);
		trace(e.toString()); // static extension works
		trace(Std.string(e)); // but can't override the default toString impl
	}
}

class EntryValueTools {
	public static function toString(v:EntryValue) {
		return switch v {
			case Integer(i): 'Integer(0x${StringTools.hex(i, 2)})';
		}
	}
}

@:using(Main.EntryValueTools)
enum EntryValue {
	Integer(i:Int);
	
	// public function toString():String; // perhaps support toString function inside enum itself?
}

ref: HaxeFoundation/haxe-evolution#10

@RealyUniqueName RealyUniqueName added this to the Backlog milestone Jan 28, 2021
@RealyUniqueName
Copy link
Member

What's the point of Std.string(e) here instead of just tracing e?
I guess the only case for that is when the type of e is not known to be the enum at compile time.

@back2dos
Copy link
Member

I guess the point is that as soon as you want to trace something that contains the enum, e.g. Array<EntryValueTools>, the static extension isn't used.

@Simn
Copy link
Member

Simn commented Feb 16, 2021

Std.string(e) is nothing more than a run-time call so of course static extensions don't apply.

This would be a new feature where the printing implementation somehow routes to a custom function for enums. On some targets we might be able to cheat by actually injecting toString methods into the generated code, but eeeh...

Either way, this would require a haxe-evolution that considers all targets, and probably also the "" + enum situation. I agree that this would be nice to have, but it's going to require quite a bit of effort.

@Simn Simn closed this as completed Feb 16, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants