Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ToString() implicitly in Delphi objects or strings?

Tags:

java

delphi

Delphi is like an England Queen Guard. It does not like ambiguity and may even kill to protect the hard code. But Java is almost a street corner woman. When I use this is java:

 Button button = new Button();
 String a = "This is a " + button;

I get This is a button

But if I do that in Delphi:

 ShowMessage('This is a ' + Button1);

I get an error, because Delphi has toString() method (now) but it does not implicitly calls it. Because literal strings are not objects in OP. The correct use is:

 ShowMessage('This is a ' + Button1.toString());

Is there any way to override this behave so it works like Java?

For reference: How an object will call toString method implicitly?

like image 641
NaN Avatar asked Dec 15 '22 09:12

NaN


1 Answers

There's no way to enforce an implicit cast or method call on an object instance.

If this was a record that you controlled then you could implement an Implicit class operator that would perform a cast to string.

The issue discussed link that you refer to is simply an implementation detail of PrintStream.println(). That relies on the ability of String.valueOf() to come up with a string representation for any object which in turn relies on Object.toString(). In fact the discussion there concerning println() is unrelated to the way the + operator in Java works which is the pertinent issue in your question.

Delphi's TObject has a virtual ToString method that could be used to perform the same purpose. So it would be easy enough to use the exact same technique as PrintStream.println() in Delphi code.

like image 67
David Heffernan Avatar answered Feb 02 '23 01:02

David Heffernan