Swan Lake Beta3 is here.
import ballerina/io;

type Headers record {
   string 'from;
   string to;

   // Records can have optional fields
   string subject?;

};

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

//Use ?. operator to access 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 can be marked as optional. These fields can be omitted when creating a record. 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.

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 ?. operator to access 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:
import ballerina/io;

type Headers record {
   string 'from;
   string to;

   // Records can have optional fields
   string subject?;

};

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

//Use ?. operator to access 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 can be marked as optional. These fields can be omitted when creating a record. 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.

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 ?. operator to access 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:
Subscribe to the newsletter

In the creation of Ballerina, we were inspired by so many technologies. Thank you to all that have come before us (and forgive us if we missed one): Java, Go, C, C++, D, Rust, Haskell, Kotlin, Dart, TypeScript, JavaScript, Python, Perl, Flow, Swift, Elm, RelaxNG, NPM, Crates, Maven, Gradle, Kubernetes, Docker, Envoy, Markdown, GitHub and WSO2.

Cookie Policy

This website uses cookies so that we can provide you with the best user experience. Read our Cookie Policy to find out more.

If you wish to disable cookies you can do so from your browser.

I Understand