Generic Objects question
Monkey Forums/Monkey Programming/Generic Objects question
| ||
I'm having some trouble grasping how to store generic objects. For example:Class player Field x:float Field y:float Field data:Object '...etc End Class ... ... myPlayer:player = New player() myPlayer:data="Test" 'Store a string object? ... ... 'Retreive the string object Print myPlayer.data I know its not a great example, but aren't strings Objects in Monkey? Is this the correct way to go about this? I'm sure it has something to do with casting - can anyone point me in the right direction? thanks! |
| ||
you would have to create a string object class class string_object field str$ end class to go into the data field unless every player's data is going to be a string then just use string. Also if every player's data is going to be a Bool,String,Int or Float you can convert them to strings to go into field data:String |
| ||
The monkey module has boxes.monkey, which contains classes for wrapping primitive types as objects. |
| ||
The Object Class is not compatible with the String Class. If you need generic data, you can use <T> type parameters or even use overloaded Getter/Setters. Class Generic<T> Field data:T Method WhatType() If Int(data) =data Print "Int" Elseif Float(data) =data Print "Float" Elseif String(data) =data Print "String" Else Print "Unknown" Endif End End ''use it like this Local gs:Generic<String> = New Generic<String> gs.data = "hello" Local gf:Generic<Float> = New Generic<Float> gf.data = 2.45 gs.WhatType() ''prints String gf.WhatType() ''prints Float |
| ||
what is this signs means <X> in a class definition? |
| ||
what is this signs means <X> in a class definition? It is a TYPE PARAMETER, also used in C++ programming. It means you can define a Class without a specific type, and in its place use "X". BUT-- when you use NEW you will need to define your type by using New Class<Int>. Or New Class<Float>. Or New Class<OtherClass>. This is also how List<X> works. |