Generics wildcard operator

Monkey Forums/Monkey Programming/Generics wildcard operator

Samah(Posted 2011) [#1]
One of the brilliant things about generics in Java is the wildcard operator ? (question mark).
It basically lets you say "I don't know what this type is".
Here's an example.

Strict

Function Main:Int()
	Local truck:Truck = New Truck
	Local car:Car = New Car
	Local trucks:List<Truck> = New List<Truck>
	Local cars:List<Car> = New List<Car>
	
	' works because Truck and Car extend Vehicle
	ServiceVehicle(truck)
	ServiceVehicle(car)
	
	' does not work because List<Truck> and List<Car> do not extend List<Vehicle>
	ServiceVehicles(trucks)
	ServiceVehicles(cars)
	
	Return 0
End

Class Vehicle
End

Class Truck Extends Vehicle
End

Class Car Extends Vehicle
End

Function ServiceVehicle:Void(vehicle:Vehicle)
End

Function ServiceVehicles:Void(vehicles:List<Vehicle>)
End


As it stands, this will not compile. This is because although Truck and Car extend Vehicle, List<Truck> and List<Car> do NOT extend List<Vehicle>. This is correct for any generics implementation.
In order for this to work, we need to use a wildcard.

Function ServiceVehicles:Void(vehicles:List<? Extends Vehicle>)
End


Using a wildcard like so tells the compiler "I don't know what type of object this List contains, but I know that it extends Vehicle."
This way you can take objects from the vehicles List and know for a fact that they are definitely Vehicles. You can typecast them later to find out which one.

Could we have this functionality added please? I know it's a big ask, but generics are very limited without it.

Edit:
The downside is that for correct implementation, wildcarded Lists should be readonly. Otherwise, we could pass a List<Truck> through to the wildcard variable, then add Cars to it since they match the wildcard.


marksibly(Posted 2011) [#2]
Hi,

Interesting stuff!

My template experience is mostly based on C++ which doesn't have anything like this. But as such, I don't consider generics to be 'very limited without it' as I've been using C++ for a while now and have managed.

To be honest, implementing something like this is a LONG way down the road, as I have several other features I consider to be more important which I would like to implement first. But I'll keep this in mind...


Samah(Posted 2011) [#3]
Grrr.... this messes up the Collections framework I'm writing. :(
Never mind, I'll have to rethink some of it.

Thanks anyway.