How Delegates could be easily added to Trans

Monkey Forums/Monkey Programming/How Delegates could be easily added to Trans

ziggy(Posted 2014) [#1]
EDIT: Thinking a bit more deeply about this idea design, I think it is not functional for a number of reasons, I'll leave it here just in case anyone gets a better idea

After spending lots of time trying to get a decent event system using Reflection, and trying to avoid the Java-like idea of manually implementing interfaces for any event in a gui system, I got to a possible way to implement proper delegates in Trans.
This is just an idea:

Class MyClass
	Method DrawMe(x:Int, y:Int)
		
	End
End

Delegate MyDelegate AddressOf MyClass.DrawMe(x:Int, y:Int) 	'This internally generates the delegate interface

Function Main()

	Local b:= New MyClass

	'This internally generates a instance of the MyDelegate class. (see below)
	Local del:MyDelegate = New MyDelegate(b)
	
	del.invoke(100, 200)	'This call the defined method with the given parameters, using the provided instance on "del" declaration
	
End


What should trans internally do:

When parsing Delegate:

'1.- Create an Interface called MyDelegate_interface like this: (ideally it would be called MyDelegate_Interface@@ or something like this).
Interface MyDelegate_interface
	Method DrawMe(x:Int, y:Int)
End


'2.- Add the Implements directive to the MyClass declaration
Class MyClass Implements MyDelegate_interface


3.- Create the MyDelegate class, so it can be instantiated and passed to functions, methods, added to lists, etc.
Class MyDelegate implements DelegateInvoker
	Method New(base:MyDelegate_interface)
		caller = base
	End
	
	Method Invoke(params)
		caller.DrawMe(params)
	End
	
	Private
	Field caller:MyDelegate_interface
	
End


'When the Invoke is called, it's just a regular method call:
del.Invoke(parameters ...)

Doing it this way, delegates would be regular Monkey objects, no reflection involved, and not too much additional code is generated. I think it should be easy to implement in Trans, I just haven't really looked deeply at it enough to implement it myself, but if anyone wants to lend a hand, or if Mark reads this and likes the idea, I would be more than grateful.

Abviously, somewhere in the language, we would need to define this:
Interface DelegateInvoker
    Method Invoke(params)
End

Params can be an object array, or something like this.


Nobuyuki(Posted 2014) [#2]
Delegates are terrible. Lambda expressions and interfaces can do pretty much everything delegates can with less confusion and unsafe nastiness. Just my 2 cents


ziggy(Posted 2014) [#3]
No, they can't! You can't change dynamicaly at runtime what method an interface implements. That's exactly what I'm trying to achieve and where I think delegates shine. Also, not sure what's unsafe about them... ?