Composite Types

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.

Composite Type Declaration and Creation

Structures are declared using the struct keyword and resources are declared using the resource keyword. The keyword is followed by the name.

1
pub struct SomeStruct {
2
// ...
3
}
4
5
pub 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 constant
2
let 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 constant
2
let b <- create SomeResource()

Composite Type Fields

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 KindAssignableKeyword
Variable fieldYesvar
Constant fieldNolet

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:

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 field
2
// 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 allow
7
// the fields to be read in outer scopes. Fields can also be declared
8
// private so they cannot be accessed in outer scopes.
9
// Access control will be explained in a later section.
10
//
11
pub struct Token {
12
pub let id: Int
13
pub var balance: Int
14
15
init(id: Int, balance: Int) {
16
self.id = id
17
self.balance = balance
18
}
19
}

Note that it is invalid to provide the initial value for a field in the field declaration.

1
pub 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
//
5
pub let id: Int = 1
6
}

The field access syntax must be used to access fields – fields are not available as variables.

1
pub struct Token {
2
pub let id: Int
3
4
init(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
//
8
id = initialID
9
}
10
}

The initializer is not automatically derived from the fields, it must be explicitly declared.

1
pub struct Token {
2
pub let id: Int
3
4
// 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.

1
let token = Token(id: 42, balance: 1_000_00)
2
3
token.id // is `42`
4
token.balance // is `1_000_000`
5
6
token.balance = 1
7
// `token.balance` is `1`
8
9
// Invalid: assignment to constant field
10
//
11
token.id = 23

Initializers do not support overloading.

Composite Type Functions

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 rectangle
2
// and has variable fields for the width and height.
3
//
4
pub struct Rectangle {
5
pub var width: Int
6
pub var height: Int
7
8
init(width: Int, height: Int) {
9
self.width = width
10
self.height = height
11
}
12
13
// Declare a function named "scale", which scales
14
// the rectangle by the given factor.
15
//
16
pub fun scale(factor: Int) {
17
self.width = self.width * factor
18
self.height = self.height * factor
19
}
20
}
21
22
let rectangle = Rectangle(width: 2, height: 3)
23
rectangle.scale(factor: 4)
24
// `rectangle.width` is `8`
25
// `rectangle.height` is `12`

Functions do not support overloading.

Composite Type Subtyping

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
//
4
struct A {
5
fun test() {}
6
}
7
8
// Declare a structure named `B` which has a function `test`
9
// which has type `((): Void)`.
10
//
11
struct B {
12
fun test() {}
13
}
14
15
// Declare a variable named which accepts values of type `A`.
16
//
17
var something: A = A()
18
19
// 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
//
24
something = B()
25
26
// Valid: Reassign a new value of type `A`.
27
//
28
something = A()

Composite Type Behaviour

Structures

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
//
3
pub struct SomeStruct {
4
pub var value: Int
5
6
init(value: Int) {
7
self.value = value
8
}
9
10
fun increment() {
11
self.value = self.value + 1
12
}
13
}
14
15
// Declare a constant with value of structure type `SomeStruct`.
16
//
17
let a = SomeStruct(value: 0)
18
19
// *Copy* the structure value into a new constant.
20
//
21
let b = a
22
23
b.value = 1
24
// NOTE: `b.value` is 1, `a.value` is *`0`*
25
26
b.increment()
27
// `b.value` is 2, `a.value` is `0`

Accessing Fields and Functions of Composite Types Using Optional Chaining

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.
2
pub struct Value {
3
pub var number: Int
4
5
init() {
6
self.number = 2
7
}
8
9
pub fun set(new: Int) {
10
self.number = new
11
}
12
13
pub fun setAndReturn(new: Int): Int {
14
self.number = new
15
return new
16
}
17
}
18
19
// Create a new instance of the struct as an optional
20
let value: Value? = Value()
21
// Create another optional with the same type, but nil
22
let noValue: Value? = nil
23
24
// Access the `number` field using optional chaining
25
let twoOpt = value?.number
26
// Because `value` is an optional, `twoOpt` has type `Int?`
27
let two = twoOpt ?? 0
28
// `two` is `2`
29
30
// Try to access the `number` field of `noValue`, which has type `Value?`.
31
// This still returns an `Int?`
32
let nilValue = noValue?.number
33
// This time, since `noValue` is `nil`, `nilValue` will also be `nil`
34
35
// Try to call the `set` function of `value`.
36
// The function call is performed, as `value` is not nil
37
value?.set(new: 4)
38
39
// Try to call the `set` function of `noValue`.
40
// The function call is *not* performed, as `noValue` is nil
41
noValue?.set(new: 4)
42
43
// Call the `setAndReturn` function, which returns an `Int`.
44
// Because `value` is an optional, the return value is type `Int?`
45
let sixOpt = value?.setAndReturn(new: 6)
46
let six = sixOpt ?? 0
47
// `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.
2
pub struct Value {
3
pub var number: Int
4
5
init() {
6
self.number = 2
7
}
8
9
pub fun set(new: Int) {
10
self.number = new
11
}
12
13
pub fun setAndReturn(new: Int): Int {
14
self.number = new
15
return new
16
}
17
}
18
19
// Create a new instance of the struct as an optional
20
let value: Value? = Value()
21
// Create another optional with the same type, but nil
22
let noValue: Value? = nil
23
24
// Access the `number` field using force-optional chaining
25
let two = value!.number
26
// `two` is `2`
27
28
// 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 revert
31
let number = noValue!.number
32
33
// Call the `set` function of the struct
34
35
// This succeeds and sets the value to 4
36
value!.set(new: 4)
37
38
// Run-time error: Since `noValue` is nil, the value is not set
39
// and the program execution reverts.
40
noValue!.set(new: 4)
41
42
// 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`
45
let six = value!.setAndReturn(new: 6)
46
// `six` is `6`

Resources

Resources are explained in detail in the following page.