Field access is expressed by using the dot .
followed by the name of the field.
object.fieldName
This syntax is also used to access types within packages in the form of pack.Type
.
The typer ensures that an accessed field actually exist and may apply transformations depending on the nature of the field. If a field access is ambiguous, understanding the resolution order may help.
Null-safe field access is expressed using the ?.
operator. Such access checks if the object is not null
first, and only then accesses the given field. If the object is null
, then the entire expression has the value null
.
object?.fieldName
This is roughly the same as:
(object != null ? object.fieldName : null)
However, object
is not evaluated twice.
The null-safe field access can be chained, allowing a much cleaner access to deeply nested data where each step may be null
, which may be the case when dealing with externs in a dynamically typed language, for example.