So Print can print any object

Monkey Forums/Monkey Programming/So Print can print any object

Shinkiro1(Posted 2013) [#1]
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.


Gerry Quinn(Posted 2013) [#2]
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!


slenkar(Posted 2013) [#3]
I didnt know this, thanks


ziggy(Posted 2013) [#4]
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



tiresius(Posted 2013) [#5]
I've seen that ability in other languages but it is cool to see Monkey handle it.