import ballerina/io;
function println(string|int value) {
    io:println(value);
}
function getValue(string key) returns string|error {
    if (key == "") {
        error err = error("key '" + key + "' not found");
        return err;
    } else {
        return "this is a value";
    }
}public function main() {
    println("This is a string");
    println(101);
    string|error valueOrError1 = getValue("name");
    io:println(valueOrError1);
    string|error valueOrError2 = getValue("");
    io:println(valueOrError2);
}# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run union_type.bal
This is a string
101
this is a value
error key '' not found

Union Types

Union types are types of which, the set of values is the union of the value spaces of its component types. For example, you can use a variable of a union type to store a string or an int, but there is only one type of value at any given time. Syntactically, you can define a union type with component types separated by a “|” (i.e., a vertical bar).

import ballerina/io;
function println(string|int value) {
    io:println(value);
}

This function expects the value parameter to be either a string or an int.

function getValue(string key) returns string|error {
    if (key == "") {
        error err = error("key '" + key + "' not found");
        return err;
    } else {
        return "this is a value";
    }
}

This function returns either a string or an error.

public function main() {
    println("This is a string");

This passes a string value.

    println(101);

This passes an int value.

    string|error valueOrError1 = getValue("name");
    io:println(valueOrError1);

This function call returns a string value.

    string|error valueOrError2 = getValue("");
    io:println(valueOrError2);
}

This call returns an error.

# To run this sample, navigate to the directory that contains the
# `.bal` file, and execute the `ballerina run` command below.
ballerina run union_type.bal
This is a string
101
this is a value
error key '' not found