Anything like ObjectiveC's Categories?

Monkey Forums/Monkey Programming/Anything like ObjectiveC's Categories?

Ken(Posted 2013) [#1]
In Objective C you can extend classes arbitrarily using Categories, and then the Classes behave as if they had those methods all along. Categories can even access internal variables.

That would be a useful thing in Monkey.

Say, for example, I want to print out an IntList.

Yes, I could certainly write the functions to do that:

Function PrintIntList:Void(il:IntList)
	Local s:String=""
	For local i:Int = Eachin il
		If s.Length>0 Then
			s+=", "
		EndIf
		s+=String(i)
	End
	Print s
End


But then I've littered my namespace with PrintIntList, PrintStringList, etc.

Is there a more elegant way?

I'm imagining something like

' Perhaps Print(IntList)?
' Perhaps IntList.Print
Category IntList+Print
	Method Print:Void()
		Local s:String=""
		For local i:Int = Eachin il
			If s.Length>0 Then
				s+=", "
			EndIf
			s+=String(i)
		End
		Print s
	End
End


Then, any time there's a Print(IntList) this new Print method gets called just as if it were a built-in part of the class.

Any chance of this already existing somehow? The error message of "Error: Unable to find overload for Print(IntList)" makes me think that if somehow I could just provide that overload...

-Ken


Samah(Posted 2013) [#2]
I asked for this over a year ago, but there was no official response. It's a pretty big ask to implement this for all targets, and I don't blame Mark for not wanting to touch it.
http://www.monkeycoder.co.nz/Community/posts.php?topic=2314#22616

Edit:
As to your Print example, I think it would be better to have a solution similar to Java's, where all objects inherit a ToString() method, which can be optionally overridden to provide more information.

Then:
[monkeycode]Function Print(o:Object)
Print(o.ToString())
End[/monkeycode]


ziggy(Posted 2013) [#3]
Just out of curiosity, is it the same like extension methods? http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx I haven't touched Objective-C


Ken(Posted 2013) [#4]
Hey Ziggy,

I've not used C#, but from the web page, I'd say it's exactly like extension methods.

Samah, yeah, that'd be a good idea too. In Objective-C anything that inherits from NSObject has a description method that's stubbed out to just print the class name...but you can override that and provide as much information as you want. When you start getting data structures that contain data structures, it can be a real godsend in debugging.

Of course, it's even better with a live debugger, but that's just me dreaming...:^)

-Ken