import ballerina/io;

type Headers record {
   string 'from;
   string to;

   // Records can have optional fields.
   string subject?;

};

Headers h = {
  'from: "John",
  to: "Jill"
};

// Use the `?.` operator to access the optional field.
string? subject = h?.subject;

public function main() {
    io:println("Header value: ", h);
    io:println("Subject value:", subject);
}

Optional fields

Fields of a record type can be marked as optional. These fields can be omitted when creating a value of the record type. Such fields can be accessed via optional field access (e.g., p?.name) or member access (e.g., p["name"]), which will both return () if the field is not present in the record value.

import ballerina/io;
type Headers record {
   string 'from;
   string to;
   string subject?;

Records can have optional fields.

};
Headers h = {
  'from: "John",
  to: "Jill"
};
string? subject = h?.subject;

Use the ?. operator to access the optional field.

public function main() {
    io:println("Header value: ", h);
    io:println("Subject value:", subject);
}
bal run optional_fields.bal
Header value: {"from":"John","to":"Jill"}
Subject value: