Skip to content

Moshi.Data API

The Moshi.Data module provides the @data macro for defining algebraic data types, along with reflection utilities for working with variants at runtime.

@data

@data <mutable_kw> <head> <body>

@data

Create a new algebraic data type (also known as a sum type) with the given head and variants.

data_type

data_type(variant::Type) -> Type

Return the data type of the given variant type.

data_type_name

data_type_name(x) -> Symbol

Return the data type name of the given variant.

is_data_type

is_data_type(x) -> Bool

Check if the given object is a variant of a algebraic data type.

is_variant_type

is_variant_type(x) -> Bool

Check if the given object is a variant type.

isa_variant

isa_variant(x, variant::Type) -> Bool

Check if the given variant is an instance of the given variant type.

show_variant

show_variant(io::IO, mime::Base.Multimedia.MIME{Symbol("text/plain")}, x)

Print the variant to the given IO stream in multiple lines.

Print the variant to the given IO stream in a single line.

storage_types

storage_types(value::Type) -> Base.ImmutableDict{DataType, DataType}

Return the storage types of the data type.

!!! note This method is used by the pattern matching system to extract the field of the variant.

variant_fieldnames

variant_fieldnames(value)

Return the field names of the variant.

variant_fieldtypes

variant_fieldtypes(type::Type) -> Tuple

Return the field types of the variant.

variant_getfield

variant_getfield(value, tag::Type, field::Union{Int, Symbol})

Known the variant type tag, return the field of the variant by field name or index.

!!! note This method is used by the pattern matching system to extract the field of the variant. It is not intended to be used directly. Most of cases, you can use the x.field syntax to extract the field of the variant. However, Julia compiler is not able to infer the type of the variant usually, so if you care about performance, you may want to use this method in combine with variant_storage.

variant_kind

variant_kind(x) -> VariantKind

Return the kind of the variant, can be Singleton, Anonymous, or Named.

variant_name

variant_name(x) -> Symbol

Return the name of the variant.

variant_nfields

variant_nfields(value)

Return the number of fields of the variant.

variant_storage

variant_storage(value)

Return the storage object of the variant.

variant_storage_type

variant_storage_type(tag::Type) -> Type

Return the storage type of the variant.

variant_type

variant_type(x)

Return the variant type of the given variant.

variants

variants(x::Type) -> Tuple

Return a tuple of variants of the given data type.

Return a tuple of variants of the given data type.