Extending a String

Monkey Forums/Monkey Programming/Extending a String

PoliteProgrammer(Posted 2013) [#1]
Is it possible to extend a basic type, such as a string? I'm imagining doing something like this:
Class DerivedString Extends String
  ' Override for String.Trim()
  Method Trim:Void()
    ' ...
  End
End

This gives an error 'expecting identifier' when I try it. Basically, I'm wondering if it's possible to override some of the existing methods or add additional functionality to the basic types.

I'm aware that I can just do something like this:
Class myString
  Field str:String
  Method Trim()
  End
End

but an approach based on inheritance seems far cleaner for my purposes.


muddy_shoes(Posted 2013) [#2]
Monkey's string type isn't really a class so you can't extend it.


ImmutableOctet(SKNG)(Posted 2013) [#3]
Monkey's string implementation is platform specific. However, 'StringObject' could work:

'StringObject' can be found in the 'Monkey.Boxes' module. Since it's a normal Monkey-based class, it's 'passed by reference'; in other words, Monkey uses pointers (For C++ based targets anyway, most of the other targets just use their 'fake'/automated reference systems(Which use pointers anyway)). I added a 'Clone' method, just in case you ever need a clone of it.



Example:


Console output:

Output method:
HELLO WORLD.
Just using the 'Print' command:
Hello world.



For some reason, Monkey mostly treats 'StringObject' the same way as 'String', so this would be more effective than a custom class that holds a 'String'.

The only other way is to use a custom class, or to use 'Extern', which would be problematic for some targets.