Generic interfaces now work!!!

Monkey Forums/Monkey Programming/Generic interfaces now work!!!

Skn3(Posted 2014) [#1]
Well i started this topic asking for advice but then as I was writing the code to post here, I sort of answered my own question!

I was looking for a generic way for a generic class to callback to a parent object using delegates (interfaces)...

I was sure that Monkey didn't allow generic interfaces, I seem to remember an error saying "Interfaces cannot be generic"...

So I tried the following code in Monkey 80b...
Function Main:Int()
	Local test:= New Test
	Local data:= New GenericDataStructure<Int>
	data.delegate = test
	data.Call(123)
	Return 0
End

Class Test Implements GenericDataStructureDelegate<Int>
	Method OnCall:Void(data:GenericDataStructure<Int>, value:Int)
		Print "value = " + value
	End
End

Class GenericDataStructure<T>
	Field delegate:GenericDataStructureDelegate<T>
	
	Method Call:Void(value:Int)
		delegate.OnCall(Self, value)
	End
End

Interface GenericDataStructureDelegate<T>
	Method OnCall:Void(data:GenericDataStructure<T>, value:Int)
End


And to my surprise.... IT WORKS!

AWESOME!


tiresius(Posted 2014) [#2]
What can this be used for? Or needed for particular design pattern?
I want to get excited too.


Skn3(Posted 2014) [#3]
Class World<T>
    Field tiles:T[]

    Field delegate:WorldDelegate<T>

    Method FindPath()
        'Do path findin here
        delegate.OnPathFound(self,steps)
    End
End

Interface WorldDelegate<T>
    Method OnPathFound(world:World<T>,steps:Int[])
End

Class MyApp Implements WordDelegate<Int>
    Field world:World<Int>

    Method OnCreate()
        world = new World<Int>
        world.delegate = self
    End

    Method OnPathFound(world:World<Int>,steps:Int[])
        If world = self.world
            'Do something
        EndIf
    End
End


Something like this...


ziggy(Posted 2014) [#4]
It's a sort of poor man's generics or a reasonable way to implement method pointers. It can be very handy sometimes


itto(Posted 2014) [#5]
This is great news, but is it a feature of the language now or just a temporary hack (or maybe a bug)? Before starting to use this I would like to be sure it won't break later on.


ziggy(Posted 2014) [#6]
It's a language improvement available since Monkey Generics work much more as c++ templates.internally.