tech

[English] [Japanese]

18. mapping

LuneScript supports converting instances of classes to and from maps.

mapping

LuneScript supports converting instances of classes to and from map objects.

Specifically, you can:

  • Create map object from class instance
  • Creating an instance of a class from a map object

This allows you, for example, to generate JSON data from class instances and vice versa.

This feature is called mapping.

To make use of mapping , we need to declare Mapping as an interface to implement when declaring the class.

For example:

// @lnsFront: ok
class Test extend (Mapping){
   let val1:int {pub};
   let val2:str {pub};
}
let test = new Test(1, "abc" );
let map = test._toMap();
print( map.val1, map.val2 ); // 1 abc
let test2 = unwrap Test._fromMap( map );
print( test2.$val1, test2.$val2 ); // 1 abc

In the example above, class Test declares a Mapping implementation.

This will internally generate the following methods:

  • fn _toMap():&Map<str,&stem>
  • static fn _fromMap(map:&Map<str,&stem>):Test!,str!

_toMap() is a method that creates a map object from an instance, and _fromMap() is a class method that creates an instance from a map object.

Note that _fromMap() returns nil if the map object does not meet the conditions for creating an instance.

Specifically, if you pass the following map object to _fromMap() of the above Test, an instance will be generated,

{
   "val1": 1,
   "val2": "abc"
}

If you pass the following map object, it will not be instantiated.

{
   "val1": 1,
   "val2": 2
}

In the case of the above map object, originally val2 should be str, but it is int and it becomes inconsistent.

A further caveat to _fromMap() is that _fromMap() checks for member type inconsistencies, but not for range.

For example, an instance can be generated even from a value that cannot be obtained originally, as long as the type is correct. However, for enums, it returns nil if the value of the map object is not defined in the enum.

Limitations of mappings

A class that implements mapping has the following restrictions on its members:

  • If you have a class instance as a member, the class must be mappable.
  • If you have a map object as a member, the key must be int, real, or str.

summary

mapping makes it easy to do things like generate JSON data from class instances.

Next time, I'll explain the nil conditional operator.