Generic Classes Explanation?

Community Forums/Monkey Talk/Generic Classes Explanation?

QuickSilva(Posted 2011) [#1]
Please could someone explain what generic classes are for in Monkey (or in general) as I am having real trouble understanding the description in the docs.

Thanks for any help,
Jason.


therevills(Posted 2011) [#2]
In real basic terms you create a list which can only hold a certain type of class.

For example:

Field aliens:List<Alien>


So you would say "aliens is a list of Alien(s)"... when you add objects to the list you can only ever add an Alien object to aliens.


Yasha(Posted 2011) [#3]
The important part is that the type List<Alien> isn't the same as the type List (which is incomplete - the compiler doesn't know what type the values are) or BlitzMax's TList, which is like List<Object> (something you should never use). It's a distinct type from List<Kitten> and List<List<Alien>> as well. In each case, at compile-time, the language knows the type of the objects in the list.

Unlike BlitzMax, this means two things:

- You can only ever put an object in a List specified with that value type. So no more mixed lists of objects that don't share a common interface or base class, which you could do in BlitzMax.

- You don't have to cast the value of a list element, and succeed or get Null; the value already is of the right type for your needs. This means that you can program without checks for Null or failed cast exceptions or whatever Monkey does to check type, because the List is guaranteed to hold values of the type you're trying to read as long as there are values to read at all.

In short, what it's for is to make your code shorter and easier to read. They don't do anything you couldn't do with BlitzMax, but they stop you making a lot of stupid mistakes you could have made with it, and reduce the need for as much bumph to check that everything works as expected, both in your code, and actually having to be done at runtime (generics are filtered out during the compilation process, so they should result in faster code).


QuickSilva(Posted 2011) [#4]
Thanks guys, I understand now. Just needed to hear it in a more practical situation.

Jason.