How to test if something implements

Monkey Forums/Monkey Programming/How to test if something implements

slenkar(Posted 2011) [#1]
consider this:

Interface gasoline_user
Method refuel:Void()
End Interface

Global vehicle_list:List<vehicle>

Class vehicle

End Class

Class car Extends vehicle Implements gasoline_user
Field fuel
Method refuel:Void()
End Method
End Class

Class bus Extends vehicle Implements gasoline_user
Field fuel
Method refuel:Void()
End Method
End Class


Class bike Extends vehicle

End Class

Function Main:Int()
Local c:car=New car
Local b:bike=New bike
local bu:bus=new bus
vehicle_list=New List<vehicle>
vehicle_list.AddLast(c)
vehicle_list.AddLast(b)
vehicle_list.AddLast(bu)

For Local v:vehicle=Eachin vehicle_list
If gasoline_user(v)
Print "yes"
Endif
Next
Return 0
End Function


how do you go through the vehicle list to see which ones are gasoline users?


Goodlookinguy(Posted 2011) [#2]
Make a variable and add a assignment statement for that variable in the class' constructor based on whether or not it uses gasoline. An interface isn't going to do what you want it to do.




slenkar(Posted 2011) [#3]
thanks, that makes more sense :)


muddy_shoes(Posted 2011) [#4]
You can cast to the base object and back:

If gasoline_user(Object(v))


Horrible, but it works.


Goodlookinguy(Posted 2011) [#5]
Whoa, wait, what? Should that be legal? I've never heard of interfaces being used this way before. Is this a Monkey thing or did I miss something about OOP somewhere along the way? Please enlighten me with knowledge or a link if I did.

Edit: Oh, I got it. Never really used interfaces myself, so I didn't think about how they're used in libraries. And to check if they implement a certain interface. Though...I still find it very much unnecessary.


muddy_shoes(Posted 2011) [#6]
The Monkey weirdness is having to cast to Object before casting back to the interface. The idea of testing an object against an interface as a class/type is pretty standard: http://www.google.co.nz/search?hl=en&safe=off&q=test+if+object+implements+interface


Samah(Posted 2011) [#7]
The Monkey weirdness is having to cast to Object before casting back to the interface.

Yes, it's a bug in Monkey. Having said that, abusing "is a" checks is bad practice, really. Generics are there so that you don't have to typecast too often. Unfortunately, Monkey still doesn't support generics for interfaces.


slenkar(Posted 2011) [#8]
I coded myself into a dead-end and this really helped

If gasoline_user(Object(v))


thanks


AdamRedwoods(Posted 2011) [#9]
nm