Run-time Types
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 in Kotlin, and T.class in Java.
For example, to represent the type Int at run-time:
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:
resource Collectible {}
let collectibleType = Type<@Collectible>()
// `collectibleType` has type `Type`Type values are comparable.
Type<Int>() == Type<Int>()
Type<Int>() != Type<String>()The function 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,
// Declare a variable named `collectible` that has the *static* type `Collectible`
// and has a resource of type `Collectible`
//
let collectible: @Collectible <- create Collectible()
// The resource is an instance of type `Collectible`,
// because the concrete run-time type is `Collectible`
//
collectible.isInstance(Type<@Collectible>()) // is `true`
// The resource is an instance of type `AnyResource`,
// because the concrete run-time type `Collectible` is a subtype of `AnyResource`
//
collectible.isInstance(Type<@AnyResource>()) // is `true`
// The resource is *not* an instance of type `String`,
// because the concrete run-time type `Collectible` is *not* a subtype of `String`
//
collectible.isInstance(Type<String>()) // is `false`Note that the concrete run-time type of the object is used, not the static type.
For example, this allows implementing a marketplace sale resource:
Last updated
Was this helpful?