Composite types allow composing simpler types into more complex types, i.e., they allow the composition of multiple values into one. Composite types have a name and consist of zero or more named fields, and zero or more functions that operate on the data. Each field may have a different type.
Composite types can only be declared within a contract and nowhere else.
There are two kinds of composite types. The kinds differ in their usage and the behaviour when a value is used as the initial value for a constant or variable, when the value is assigned to a variable, when the value is passed as an argument to a function, and when the value is returned from a function:
-
Structures are copied, they are value types.
Structures are useful when copies with independent state are desired.
-
Resources are moved, they are linear types and must be used exactly once.
Resources are useful when it is desired to model ownership (a value exists exactly in one location and it should not be lost).
Certain constructs in a blockchain represent assets of real, tangible value, as much as a house or car or bank account. We have to worry about literal loss and theft, perhaps even on the scale of millions of dollars.
Structures are not an ideal way to represent this ownership because they are copied. This would mean that there could be a risk of having multiple copies of certain assets floating around, which breaks the scarcity requirements needed for these assets to have real value.
A structure is much more useful for representing information that can be grouped together in a logical way, but doesn't have value or a need to be able to be owned or transferred.
A structure could for example be used to contain the information associated with a division of a company, but a resource would be used to represent the assets that have been allocated to that organization for spending.
Nesting of resources is only allowed within other resource types, or in data structures like arrays and dictionaries, but not in structures, as that would allow resources to be copied.
Structures are declared using the struct
keyword
and resources are declared using the resource
keyword.
The keyword is followed by the name.
1pub struct SomeStruct {2// ...3}45pub resource SomeResource {6// ...7}
Structures and resources are types.
Structures are created (instantiated) by calling the type like a function.
1// instantiate a new struct object and assign it to a constant2let a = SomeStruct()
The constructor function may require parameters if the initializer of the composite type requires them.
Composite types can only be declared within contracts and not locally in functions.
Resource must be created (instantiated) by using the create
keyword
and calling the type like a function.
Resources can only be created in functions and types that are declared in the same contract in which the resource is declared.
1// instantiate a new resource object and assign it to a constant2let b <- create SomeResource()
Fields are declared like variables and constants. However, the initial values for fields are set in the initializer, not in the field declaration. All fields must be initialized in the initializer, exactly once.
Having to provide initial values in the initializer might seem restrictive, but this ensures that all fields are always initialized in one location, the initializer, and the initialization order is clear.
The initialization of all fields is checked statically and it is invalid to not initialize all fields in the initializer. Also, it is statically checked that a field is definitely initialized before it is used.
The initializer's main purpose is to initialize fields, though it may also contain other code.
Just like a function, it may declare parameters and may contain arbitrary code.
However, it has no return type, i.e., it is always Void
.
The initializer is declared using the init
keyword.
The initializer always follows any fields.
There are three kinds of fields:
-
Constant fields are also stored in the composite value, but after they have been initialized with a value they cannot have new values assigned to them afterwards. A constant field must be initialized exactly once.
Constant fields are declared using the
let
keyword. -
Variable fields are stored in the composite value and can have new values assigned to them.
Variable fields are declared using the
var
keyword.
Field Kind | Assignable | Keyword |
---|---|---|
Variable field | Yes | var |
Constant field | No | let |
In initializers, the special constant self
refers to the composite value
that is to be initialized.
If a composite type is to be stored, all its field types must be storable. Non-storable types are:
- Functions
- Accounts (
AuthAccount
/PublicAccount
) - Transactions
- References: References are ephemeral. Consider storing a capability and borrowing it when needed instead.
Fields can be read (if they are constant or variable) and set (if they are variable),
using the access syntax: the composite value is followed by a dot (.
)
and the name of the field.
1// Declare a structure named `Token`, which has a constant field2// named `id` and a variable field named `balance`.3//4// Both fields are initialized through the initializer.5//6// The public access modifier `pub` is used in this example to allow7// the fields to be read in outer scopes. Fields can also be declared8// private so they cannot be accessed in outer scopes.9// Access control will be explained in a later section.10//11pub struct Token {12pub let id: Int13pub var balance: Int1415init(id: Int, balance: Int) {16self.id = id17self.balance = balance18}19}
Note that it is invalid to provide the initial value for a field in the field declaration.
1pub struct StructureWithConstantField {2// Invalid: It is invalid to provide an initial value in the field declaration.3// The field must be initialized by setting the initial value in the initializer.4//5pub let id: Int = 16}
The field access syntax must be used to access fields – fields are not available as variables.
1pub struct Token {2pub let id: Int34init(initialID: Int) {5// Invalid: There is no variable with the name `id` available.6// The field `id` must be initialized by setting `self.id`.7//8id = initialID9}10}
The initializer is not automatically derived from the fields, it must be explicitly declared.
1pub struct Token {2pub let id: Int34// Invalid: Missing initializer initializing field `id`.5}
A composite value can be created by calling the constructor and providing the field values as arguments.
The value's fields can be accessed on the object after it is created.
1let token = Token(id: 42, balance: 1_000_00)23token.id // is `42`4token.balance // is `1_000_000`56token.balance = 17// `token.balance` is `1`89// Invalid: assignment to constant field10//11token.id = 23
Initializers do not support overloading.
Composite types may contain functions.
Just like in the initializer, the special constant self
refers to the composite value
that the function is called on.
1// Declare a structure named "Rectangle", which represents a rectangle2// and has variable fields for the width and height.3//4pub struct Rectangle {5pub var width: Int6pub var height: Int78init(width: Int, height: Int) {9self.width = width10self.height = height11}1213// Declare a function named "scale", which scales14// the rectangle by the given factor.15//16pub fun scale(factor: Int) {17self.width = self.width * factor18self.height = self.height * factor19}20}2122let rectangle = Rectangle(width: 2, height: 3)23rectangle.scale(factor: 4)24// `rectangle.width` is `8`25// `rectangle.height` is `12`
Functions do not support overloading.
Two composite types are compatible if and only if they refer to the same declaration by name, i.e., nominal typing applies instead of structural typing.
Even if two composite types declare the same fields and functions, the types are only compatible if their names match.
1// Declare a structure named `A` which has a function `test`2// which has type `((): Void)`.3//4struct A {5fun test() {}6}78// Declare a structure named `B` which has a function `test`9// which has type `((): Void)`.10//11struct B {12fun test() {}13}1415// Declare a variable named which accepts values of type `A`.16//17var something: A = A()1819// Invalid: Assign a value of type `B` to the variable.20// Even though types `A` and `B` have the same declarations,21// a function with the same name and type, the types' names differ,22// so they are not compatible.23//24something = B()2526// Valid: Reassign a new value of type `A`.27//28something = A()
Structures are copied when used as an initial value for constant or variable, when assigned to a different variable, when passed as an argument to a function, and when returned from a function.
Accessing a field or calling a function of a structure does not copy it.
1// Declare a structure named `SomeStruct`, with a variable integer field.2//3pub struct SomeStruct {4pub var value: Int56init(value: Int) {7self.value = value8}910fun increment() {11self.value = self.value + 112}13}1415// Declare a constant with value of structure type `SomeStruct`.16//17let a = SomeStruct(value: 0)1819// *Copy* the structure value into a new constant.20//21let b = a2223b.value = 124// NOTE: `b.value` is 1, `a.value` is *`0`*2526b.increment()27// `b.value` is 2, `a.value` is `0`
If a composite type with fields and functions is wrapped in an optional, optional chaining can be used to get those values or call the function without having to get the value of the optional first.
Optional chaining is used by adding a ?
before the .
access operator for fields or
functions of an optional composite type.
When getting a field value or
calling a function with a return value, the access returns
the value as an optional.
If the object doesn't exist, the value will always be nil
When calling a function on an optional like this, if the object doesn't exist, nothing will happen and the execution will continue.
It is still invalid to access an undeclared field of an optional composite type.
1// Declare a struct with a field and method.2pub struct Value {3pub var number: Int45init() {6self.number = 27}89pub fun set(new: Int) {10self.number = new11}1213pub fun setAndReturn(new: Int): Int {14self.number = new15return new16}17}1819// Create a new instance of the struct as an optional20let value: Value? = Value()21// Create another optional with the same type, but nil22let noValue: Value? = nil2324// Access the `number` field using optional chaining25let twoOpt = value?.number26// Because `value` is an optional, `twoOpt` has type `Int?`27let two = twoOpt ?? 028// `two` is `2`2930// Try to access the `number` field of `noValue`, which has type `Value?`.31// This still returns an `Int?`32let nilValue = noValue?.number33// This time, since `noValue` is `nil`, `nilValue` will also be `nil`3435// Try to call the `set` function of `value`.36// The function call is performed, as `value` is not nil37value?.set(new: 4)3839// Try to call the `set` function of `noValue`.40// The function call is *not* performed, as `noValue` is nil41noValue?.set(new: 4)4243// Call the `setAndReturn` function, which returns an `Int`.44// Because `value` is an optional, the return value is type `Int?`45let sixOpt = value?.setAndReturn(new: 6)46let six = sixOpt ?? 047// `six` is `6`
This is also possible by using the force-unwrap operator (!
).
Forced-Optional chaining is used by adding a !
before the .
access operator for fields or
functions of an optional composite type.
When getting a field value or calling a function with a return value, the access returns the value. If the object doesn't exist, the execution will panic and revert.
It is still invalid to access an undeclared field of an optional composite type.
1// Declare a struct with a field and method.2pub struct Value {3pub var number: Int45init() {6self.number = 27}89pub fun set(new: Int) {10self.number = new11}1213pub fun setAndReturn(new: Int): Int {14self.number = new15return new16}17}1819// Create a new instance of the struct as an optional20let value: Value? = Value()21// Create another optional with the same type, but nil22let noValue: Value? = nil2324// Access the `number` field using force-optional chaining25let two = value!.number26// `two` is `2`2728// Try to access the `number` field of `noValue`, which has type `Value?`29// Run-time error: This time, since `noValue` is `nil`,30// the program execution will revert31let number = noValue!.number3233// Call the `set` function of the struct3435// This succeeds and sets the value to 436value!.set(new: 4)3738// Run-time error: Since `noValue` is nil, the value is not set39// and the program execution reverts.40noValue!.set(new: 4)4142// Call the `setAndReturn` function, which returns an `Int`43// Because we use force-unwrap before calling the function,44// the return value is type `Int`45let six = value!.setAndReturn(new: 6)46// `six` is `6`
Resources are explained in detail in the following page.
There is no support for null
.
There is no support for inheritance. Inheritance is a feature common in other programming languages, that allows including the fields and functions of one type in another type.
Instead, follow the "composition over inheritance" principle, the idea of composing functionality from multiple individual parts, rather than building an inheritance tree.
Furthermore, there is also no support for abstract types. An abstract type is a feature common in other programming languages, that prevents creating values of the type and only allows the creation of values of a subtype. In addition, abstract types may declare functions, but omit the implementation of them and instead require subtypes to implement them.
Instead, consider using interfaces.