Safe union

safe_union in HIDL represents an explicitly tagged union type. This is similar to a union except safe_union keeps track of the underlying type and is compatible with Java. The safe_union type is available in Android 10 and higher for new and upgraded devices.

Syntax

A safe_union is expressed in HIDL exactly like a union or struct.

safe_union MySafeUnion {
     TypeA a;
     TypeB b;
     ...
};

Usage

At runtime, a safe_union is only ever one type. By default, it's the first type in the union. For instance, above, MySafeUnion is by default TypeA.

hidl-gen generates a custom class or struct for a safe_union in both C++ and Java. This class includes a discriminator for each member (in hidl_discriminator), a method to get the current discriminator (getDiscriminator), and setters and getters for each member. Each setter and getter is named exactly as its member. For instance, the getter for TypeA a is called "a", and it returns something of TypeA. The corresponding setter is also be called "a" and takes a parameter of TypeA. Setting the value in a safe_union updates the value of the discriminator as returned by getDiscriminator. Accessing a value from a discriminator that isn't the current discriminator aborts the program. For instance, if calling getDiscriminator on an instance of MySafeUnion returns hidl_discriminator::b, then trying to retrieve a aborts the program.

Monostate

A safe_union always has a value, but if it is desired to not have a value, use android.hidl.safe_union@1.0::Monostate as a placeholder. For instance, the following union can either be noinit (empty) or foo:

import android.hidl.safe_union@1.0::Monostate;

safe_union OptionalFoo {
     Monostate noinit;
     Foo foo;
};