Run-time Types

5 min read

Types can be represented at run-time. To create a type value, use the constructor function Type<T>(), which accepts the static type as a type argument.

This is similar to e.g. T.self in Swift, T::class/KClass<T> in Kotlin, and T.class/Class<T> in Java.

For example, to represent the type Int at run-time:

1
let intType: Type = Type<Int>()

This works for both built-in and user-defined types. For example, to get the type value for a resource:

1
resource Collectible {}
2
3
let collectibleType = Type<@Collectible>()
4
5
// `collectibleType` has type `Type`

Type values are comparable.

1
Type<Int>() == Type<Int>()
2
3
Type<Int>() != Type<String>()

The method fun isSubtype(of otherType: Type): Bool can be used to compare the run-time types of values.

1
Type<Int>().isSubtype(of: Type<Int>()) // true
2
3
Type<Int>().isSubtype(of: Type<String>()) // false
4
5
Type<Int>().isSubtype(of: Type<Int?>()) // true

To get the run-time type's fully qualified type identifier, use the let identifier: String field:

1
let type = Type<Int>()
2
type.identifier // is "Int"
1
// in account 0x1
2
3
struct Test {}
4
5
let type = Type<Test>()
6
type.identifier // is "A.0000000000000001.Test"

Getting the Type from a Value

The method fun getType(): Type can be used to get the runtime type of a value.

1
let something = "hello"
2
3
let type: Type = something.getType()
4
// `type` is `Type<String>()`

This method returns the concrete run-time type of the object, not the static type.

1
// Declare a variable named `something` that has the *static* type `AnyResource`
2
// and has a resource of type `Collectible`
3
//
4
let something: @AnyResource <- create Collectible()
5
6
// The resource's concrete run-time type is `Collectible`
7
//
8
let type: Type = something.getType()
9
// `type` is `Type<@Collectible>()`

Constructing a Run-time Type

Run-time types can also be constructed from type identifier strings using built-in constructor functions.

1
fun CompositeType(_ identifier: String): Type?
2
fun InterfaceType(_ identifier: String): Type?
3
fun RestrictedType(identifier: String?, restrictions: [String]): Type?

Given a type identifer (as well as a list of identifiers for restricting interfaces in the case of RestrictedType), these functions will look up nominal types and produce their run-time equivalents. If the provided identifiers do not correspond to any types, or (in the case of RestrictedType) the provided combination of identifiers would not type-check statically, these functions will produce nil.

1
struct Test {}
2
struct interface I {}
3
let type: Type = CompositeType("A.0000000000000001.Test")
4
// `type` is `Type<Test>`
5
6
let type2: Type = RestrictedType(
7
identifier: type.identifier,
8
restrictions: ["A.0000000000000001.I"]
9
)
10
// `type2` is `Type<Test{I}>`

Other built-in functions will construct compound types from other run-types.

1
fun OptionalType(_ type: Type): Type
2
fun VariableSizedArrayType(_ type: Type): Type
3
fun ConstantSizedArrayType(type: Type, size: Int): Type
4
fun FunctionType(parameters: [Type], return: Type): Type
5
// returns `nil` if `key` is not valid dictionary key type
6
fun DictionaryType(key: Type, value: Type): Type?
7
// returns `nil` if `type` is not a reference type
8
fun CapabilityType(_ type: Type): Type?
9
fun ReferenceType(authorized: bool, type: Type): Type

Asserting the Type of a Value

The method fun isInstance(_ type: Type): Bool can be used to check if a value has a certain type, using the concrete run-time type, and considering subtyping rules,

1
// Declare a variable named `collectible` that has the *static* type `Collectible`
2
// and has a resource of type `Collectible`
3
//
4
let collectible: @Collectible <- create Collectible()
5
6
// The resource is an instance of type `Collectible`,
7
// because the concrete run-time type is `Collectible`
8
//
9
collectible.isInstance(Type<@Collectible>()) // is `true`
10
11
// The resource is an instance of type `AnyResource`,
12
// because the concrete run-time type `Collectible` is a subtype of `AnyResource`
13
//
14
collectible.isInstance(Type<@AnyResource>()) // is `true`
15
16
// The resource is *not* an instance of type `String`,
17
// because the concrete run-time type `Collectible` is *not* a subtype of `String`
18
//
19
collectible.isInstance(Type<String>()) // is `false`

Note that the concrete run-time type of the object is used, not the static type.

1
// Declare a variable named `something` that has the *static* type `AnyResource`
2
// and has a resource of type `Collectible`
3
//
4
let something: @AnyResource <- create Collectible()
5
6
// The resource is an instance of type `Collectible`,
7
// because the concrete run-time type is `Collectible`
8
//
9
something.isInstance(Type<@Collectible>()) // is `true`
10
11
// The resource is an instance of type `AnyResource`,
12
// because the concrete run-time type `Collectible` is a subtype of `AnyResource`
13
//
14
something.isInstance(Type<@AnyResource>()) // is `true`
15
16
// The resource is *not* an instance of type `String`,
17
// because the concrete run-time type `Collectible` is *not* a subtype of `String`
18
//
19
something.isInstance(Type<String>()) // is `false`

For example, this allows implementing a marketplace sale resource:

1
pub resource SimpleSale {
2
3
/// The resource for sale.
4
/// Once the resource is sold, the field becomes `nil`.
5
///
6
pub var resourceForSale: @AnyResource?
7
8
/// The price that is wanted for the purchase of the resource.
9
///
10
pub let priceForResource: UFix64
11
12
/// The type of currency that is required for the purchase.
13
///
14
pub let requiredCurrency: Type
15
pub let paymentReceiver: Capability<&{FungibleToken.Receiver}>
16
17
/// `paymentReceiver` is the capability that will be borrowed
18
/// once a valid purchase is made.
19
/// It is expected to target a resource that allows depositing the paid amount
20
/// (a vault which has the type in `requiredCurrency`).
21
///
22
init(
23
resourceForSale: @AnyResource,
24
priceForResource: UFix64,
25
requiredCurrency: Type,
26
paymentReceiver: Capability<&{FungibleToken.Receiver}>
27
) {
28
self.resourceForSale <- resourceForSale
29
self.priceForResource = priceForResource
30
self.requiredCurrency = requiredCurrency
31
self.paymentReceiver = paymentReceiver
32
}
33
34
destroy() {
35
// When this sale resource is destroyed,
36
// also destroy the resource for sale.
37
// Another option could be to transfer it back to the seller.
38
destroy self.resourceForSale
39
}
40
41
/// buyObject allows purchasing the resource for sale by providing
42
/// the required funds.
43
/// If the purchase succeeds, the resource for sale is returned.
44
/// If the purchase fails, the program aborts.
45
///
46
pub fun buyObject(with funds: @FungibleToken.Vault): @AnyResource {
47
pre {
48
// Ensure the resource is still up for sale
49
self.resourceForSale != nil: "The resource has already been sold"
50
// Ensure the paid funds have the right amount
51
funds.balance >= self.priceForResource: "Payment has insufficient amount"
52
// Ensure the paid currency is correct
53
funds.isInstance(self.requiredCurrency): "Incorrect payment currency"
54
}
55
56
// Transfer the paid funds to the payment receiver
57
// by borrowing the payment receiver capability of this sale resource
58
// and depositing the payment into it
59
60
let receiver = self.paymentReceiver.borrow()
61
?? panic("failed to borrow payment receiver capability")
62
63
receiver.deposit(from: <-funds)
64
let resourceForSale <- self.resourceForSale <- nil
65
return <-resourceForSale
66
}
67
}