Box Classes

Monkey Forums/Monkey Programming/Box Classes

doug(Posted 2015) [#1]
What useful purpose can Box Classes actually be used for?


ImmutableOctet(SKNG)(Posted 2015) [#2]
They're mainly for reflection and sharing a variable between multiple functions/methods. Basically, they're just containers which hold the type they're named after.

For example, the 'IntObject' class holds an integer, and is needed in order to send an integer into a method or function via the 'reflection' module ('BoxInt' will generate one using the input). The other usual purpose is for passing a variable by-reference. There are some interesting uses for this, such as what my 'ioelement' module does. This particular idea can be a bit wasteful when done in "real time", as you'd be making new objects every call (This does not have to be the case). This functionality should not be confused with proper variable-reference systems like what BlitzMax and C++ have, where the position on the stack is used. Since we can't use lower level hacks like that, in Monkey we have to use a container object.

As a rule of thumb with reflection, don't make 'IntObjects' (Or similar "box" types) yourself (Unless you need to for your code), use 'BoxInt' (Or the other variations).


doug(Posted 2015) [#3]
Thanks for your quick and comprehensive reply; it was very informative. Note: I thought you could only use Box Classes on Integer, Float, or string types. At least that is what I got out of the documentation ,or maybe it was just giving a helpful suggestion on how to effectively use Box Classes.


ImmutableOctet(SKNG)(Posted 2015) [#4]
Well, the only other types are objects, booleans, and arrays; objects work like this already (Thus the purpose of the "boxes"). Booleans have the 'BoolObject' class, so they're covered. Arrays have 'ArrayObject', which is a generic/template class. There aren't any other non-object types to my knowledge.

As a side note, be careful when using box classes with function or method overloads; Monkey isn't too great about implicit type resolution when "ToBlah" (Where "Blah" is a type's name) is present. I had to write an entire support-module for my 'vector' module, just so I could use full reflection with 'IntObject' and 'FloatObject'.

I actually was going to post that initial reply earlier than I did, but I ended up being interrupted (Holidays and all that); being sick didn't help things either.