Composite Types
Composite types allow composing simpler types into more complex types. For example, 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:
- Structures are copied — they are value types. Structures are useful when copies with an 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).
Each kind differs in its usage and behavior, depending on when the value is:
- used as the initial value for a constant or variable
- assigned to a variable
- passed as an argument to a function, and
- returned from a function.
Certain constructs in a blockchain represent assets of real, tangible value, as much as a house, car, or bank account. We must consider the possiblity of 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 can be 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 and calls into question who actually owns the property.
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:
access(all)
struct SomeStruct {
// ...
}
access(all)
resource SomeResource {
// ...
}- Structures and resources are types.
- Structures are created (instantiated) by calling the type like a function.
// instantiate a new struct object and assign it to a constant
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.
- A resource must be created (instantiated) by using the
createkeyword 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.
// instantiate a new resource object and assign it to a constant
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
initkeyword. - The initializer always follows any fields.
There are two 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
letkeyword. -
Variable fields — are stored in the composite value and can have new values assigned to them.
Variable fields are declared using the
varkeyword.Field Kind Assignable Keyword Variable field Yes varConstant 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 of its field types must be storable. Non-storable types are:
- Functions
- Accounts —
Account - 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.
// Declare a structure named `Token`, which has a constant field
// named `id` and a variable field named `balance`.
//
// Both fields are initialized through the initializer.
//
// The public access modifier `access(all)` is used in this example to allow
// the fields to be read in outer scopes. Fields can also be declared
// private so they cannot be accessed in outer scopes.
//
access(all)
struct Token {
access(all)
let id: Int
access(all)
var balance: Int
init(id: Int, balance: Int) {
self.id = id
self.balance = balance
}
}It is invalid to provide the initial value for a field in the field declaration.
access(all)
struct StructureWithConstantField {
// Invalid: It is invalid to provide an initial value in the field declaration.
// The field must be initialized by setting the initial value in the initializer.
//
access(all)
let id: Int = 1
}The field access syntax must be used to access fields — fields are not available as variables.
access(all)
struct Token {
access(all)
let id: Int
init(initialID: Int) {
// Invalid: There is no variable with the name `id` available.
// The field `id` must be initialized by setting `self.id`.
//
id = initialID
}
}The initializer is not automatically derived from the fields. It must be explicitly declared.
access(all)
struct Token {
access(all)
let id: Int
// Invalid: Missing initializer initializing field `id`.
}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:
let token = Token(id: 42, balance: 1_000_00)
token.id // is `42`
token.balance // is `1_000_000`
token.balance = 1
// `token.balance` is `1`
// Invalid: assignment to constant field
//
token.id = 23Initializers do not support overloading.
Initializers can also be declared with the view keyword to indicate that they do not perform any mutating operations and to allow them to be called from within other view functions. In an initializer, writes to self are considered view (unlike within other composite functions), as the value being constructed here is by definition local to the context calling the initializer:
access(all)
struct Token {
access(all)
let id: Int
access(all)
var balance: Int
view init(id: Int, balance: Int) {
self.id = id
self.balance = balance
}
}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:
// Declare a structure named "Rectangle", which represents a rectangle
// and has variable fields for the width and height.
//
access(all)
struct Rectangle {
access(all)
var width: Int
access(all)
var height: Int
init(width: Int, height: Int) {
self.width = width
self.height = height
}
// Declare a function named "scale", which scales
// the rectangle by the given factor.
//
access(all)
fun scale(factor: Int) {
self.width = self.width * factor
self.height = self.height * factor
}
}
let rectangle = Rectangle(width: 2, height: 3)
rectangle.scale(factor: 4)
// `rectangle.width` is `8`
// `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:
// Declare a structure named `A` which has a function `test`
// which has type `fun(): Void`.
//
struct A {
fun test() {}
}
// Declare a structure named `B` which has a function `test`
// which has type `fun(): Void`.
//
struct B {
fun test() {}
}
// Declare a variable named which accepts values of type `A`.
//
var something: A = A()
// Invalid: Assign a value of type `B` to the variable.
// Even though types `A` and `B` have the same declarations,
// a function with the same name and type, the types' names differ,
// so they are not compatible.
//
something = B()
// Valid: Reassign a new value of type `A`.
//
something = A()Composite type behavior
The following describes the behavior of composite types.
Structures
Structures are copied when they are:
- used as an initial value for a constant or variable
- assigned to a different variable
- passed as an argument to a function, and
- returned from a function.
Accessing a field or calling a function of a structure does not copy it.
// Declare a structure named `SomeStruct`, with a variable integer field.
//
access(all)
struct SomeStruct {
access(all)
var value: Int
init(value: Int) {
self.value = value
}
fun increment() {
self.value = self.value + 1
}
}
// Declare a constant with value of structure type `SomeStruct`.
//
let a = SomeStruct(value: 0)
// *Copy* the structure value into a new constant.
//
let b = a
b.value = 1
// NOTE: `b.value` is 1, `a.value` is *`0`*
b.increment()
// `b.value` is 2, `a.value` is `0`Optional chaining
You can access fields and functions of composite types by 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:
// Declare a struct with a field and method.
access(all)
struct Value {
access(all)
var number: Int
init() {
self.number = 2
}
access(all)
fun set(new: Int) {
self.number = new
}
access(all)
fun setAndReturn(new: Int): Int {
self.number = new
return new
}
}- Create a new instance of the struct as an optional:
let value: Value? = Value() - Create another optional with the same type, but nil:
let noValue: Value? = nil - Access the
numberfield using optional chaining:let twoOpt = value?.number- Because
valueis an optional,twoOpthas typeInt?:
let two = twoOpt ?? 0twois2.
- Because
- Try to access the
numberfield ofnoValue, which has typeValue?. This still returns anInt?:let nilValue = noValue?.number- This time, since
noValueisnil,nilValuewill also benil.
- This time, since
- Try to call the
setfunction ofvalue. The function call is performed, asvalueis not nil:value?.set(new: 4) - Try to call the
setfunction ofnoValue. The function call is not performed, asnoValueis nil:noValue?.set(new: 4) - Call the
setAndReturnfunction, which returns anInt. Becausevalueis an optional, the return value is typeInt?:let sixOpt = value?.setAndReturn(new: 6) let six = sixOpt ?? 0sixis6.
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:
// Declare a struct with a field and method.
access(all)
struct Value {
access(all)
var number: Int
init() {
self.number = 2
}
access(all)
fun set(new: Int) {
self.number = new
}
access(all)
fun setAndReturn(new: Int): Int {
self.number = new
return new
}
}- Create a new instance of the struct as an optional:
let value: Value? = Value() - Create another optional with the same type, but nil:
let noValue: Value? = nil - Access the
numberfield using force-optional chaining:let two = value!.numbertwois2
- Try to access the
numberfield ofnoValue, which has typeValue?.- Run-time error: This time, since
noValueisnil, the program execution will revert.
let number = noValue!.number - Run-time error: This time, since
- Call the
setfunction of the struct.value!.set(new: 4)- This succeeds and sets the value to 4
noValue!.set(new: 4)- Run-time error: Since
noValueis nil, the value is not set and the program execution reverts.
- Call the
setAndReturnfunction, which returns anInt. Because we use force-unwrap before calling the function, the return value is typeInt:let six = value!.setAndReturn(new: 6)sixis6
Resources
Resources are explained in detail in this article.
Unbound references and nulls
There is no support for null.
Inheritance and abstract types
There is no support for inheritance. Inheritance is a feature common in other programming languages, which 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.