is it possible to overwrite how an Std.string transforms an object into a string?
E.g. I have a class Person.
class Person {
public var name:String;
}
However when I use:
var p:Person = new Person("Some name");
trace(Std.string(p)); // this will return something like foo.Person( bar )
but I want to have something like:
var p:Person = new Person("Some name");
trace(Std.string(p)); // should return "Person(Some name)"
Add a toString()
method to your class.
Example: https://try.haxe.org/#F7A77
It will work with Std.string()
but may not work with runtime toString()
. The trick does work at runtime for javascript target, but the toString()
method will be removed by dce (1).
You can either disable dce (I would not recommend it for javascript target) or just force the compiler to keep your toString()
function by adding a @:keep
meta:
@:keep
function toString() {
return "my object";
}