Using Mapped Types

Using mapped types is as seamless as it can get: you just use them.

Mapped types looks and behave just like a regular types, and your code can use them seamlessly, without even being aware they are mapped. You can declare variables or fields of the type, new up instances of them, and make calls to their members.

Under the hood, the compiler will do all the hard work and map everything to calls to the original classes, depending on the platform you are compiling for – but your code does not need to concern itself with that. For example, when using the [Elements RTL](/API/Elements RTL) mapped class library, you can simply write platform-independent code that will "just work" everywhere.

Casting between Mapped and Real Types

Because instances of mapped types really are instances of the original type at runtime, there are a couple of extra things you can do with mapped types:

  • You can seamlessly cast from a mapped type to the real type, for example if you need access to a more advanced function not exposed on the mapped type. Of course at this stage, the cast and the remaining code becomes platform-specific.
  • You can seamlessly cast from a real type to a mapped type. For example, you may be working with platform APIs that return concrete platform types (say a Cocoa API that returns an NSDictionary). To continue working with the type in a platform-independent way, you can just cast it to, say, a Sugar.Dictionary.

These casts are completely toll-free – meaning they are mere instructions to the compiler to now treat the type differently. They incur no runtime overhead and no conversion cost.

  • You can also seamlessly pass mapped types to functions expecting a concrete type or vise versa. This makes it extremely easy to mix platform-specific and platform-independent code. Your shared business code might define a method that expects a Sugar.XmlDocument, but it's being called from platform-specific code that just read an NSXMLDocument on Cocoa. You can call the method, and simply pass the NSXMLDocument, without ugly casts making the code more complicated.