How to test if something implements
Monkey Forums/Monkey Programming/How to test if something implements
| ||
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? |
| ||
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. |
| ||
thanks, that makes more sense :) |
| ||
You can cast to the base object and back:If gasoline_user(Object(v)) Horrible, but it works. |
| ||
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. |
| ||
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 |
| ||
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. |
| ||
I coded myself into a dead-end and this really helped If gasoline_user(Object(v)) thanks |
| ||
nm |