We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi. I'm wondering if I can return an object. Example of working code:
int x;
println(x);
In this case, x returns a value. What I want to do is to have a class that can do the same thing. How it would work would look like this:
KTibowInt x;
println(x);
Instead of returning "[sketch name][class type][memory place]", I want it to return x.y or something like that.
Answers
I your class KTibowInt create a public method called toSTring that returns a String representation of your object e.g.
This works with any user defined class.
quark, that is not quite what I was thinking of. In the example that I showed, when I type x, it returns an int, not a string.
Oh, wait... maybe it would have been more appropriate to use the Integer class. Oh, wait again... x returns itself, right? So, maybe println() does something with it.
When you use
println(x)
it creates a String representation of the variablex
and displays that in the console window. It doesn't matter what the data type ofx
is, they all work the same way.If you want to return a value from the class then create a simple getter e.g.
Now if you create the object with
x = new KTibowint(42);
then both these statements will display '42' in the console window.println(x); // uses toString method
println(x.getIntValue());
Well, I guess that's the best I can do in Processing.
Of course, in different programming languages, I could do that. But, as far as I know, this form has an answer. Still, somebody else may have a different answer.
That's the best you can do in Java, it maybe different in Javascript.
If you want something better, then you need to give a more detailed description of what you are trying to do.
Part of the problem here is the title. 'Return' has a specific meaning in Java and it's not how you're using it.
Add quark says, toString is the way to do exactly what you want. The default for objects is to print the type and address, which is pretty useless but you can override it in your own classes and make it do anything you want, as long as it returns a string. I'd add the @Override annotation to quark's solution.
Put another way, you could think of
println(x)
as "a function that callsx.toString()
". Many objects already have a toString, so println already knows what to do with them. If you create a new object, give it a toString method, and then println (the thing that calls toString) will know what to do with it (because it has a toString).See for example this related Java discussion: https://stackoverflow.com/a/29319217/7207622