So Print can print any object
Monkey Forums/Monkey Programming/So Print can print any object
| ||
I just discovered that you can use Print on any object that implements ToString(). That's really useful. For example you can write a generic function to print any object in an array (if that object implements ToString) Class ArrayHelper<T> Abstract Function PrintArray:Void(arr:T[]) For Local i:Int = 0 Until arr.Length Print arr[i] End End End Then call it like this: ArrayHelper<Color>.PrintArray(colors) (here I have used a color class which implements ToString()) Maybe that's common knowledge but to me it was completely new. Thought I would share. Edit: Ok, Bool seems to be the only type which can't be used with this. It would have to be casted to int before printing. |
| ||
It's reasonably well-known (though not to everyone, I'm sure, so no harm mentioning it), but your generic function for arrays (and obviously it can be done for any collection) is a good idea I had never thought of, and could definitely save a little hassle during debugging from time to time! |
| ||
I didnt know this, thanks |
| ||
In fact, the thing is not that you can print it. The ToString allows the instance to be passed as a string to anything expecting a string:Function Main() Local myClass:= New MyClass Local myVariable:String = myClass Print myVariable End Class MyClass Method ToString:String() Return "Rubber Soul is great" End End |
| ||
I've seen that ability in other languages but it is cool to see Monkey handle it. |