Restricted Types
// Declare a resource interface named `HasCount`,
// which has a read-only `count` field
//
resource interface HasCount {
pub let count: Int
}
// Declare a resource named `Counter`, which has a writeable `count` field,
// and conforms to the resource interface `HasCount`
//
pub resource Counter: HasCount {
pub var count: Int
init(count: Int) {
self.count = count
}
pub fun increment() {
self.count = self.count + 1
}
}
// Create an instance of the resource `Counter`
let counter: @Counter <- create Counter(count: 42)
counterRef.count // is `42`
counterRef.increment()
counterRef.count // is `43`
// Move the resource in variable `counter` to a new variable `restrictedCounter`,
// but typed with the restricted type `Counter{HasCount}`:
// The variable may hold any `Counter`, but only the functionality
// defined in the given restriction, the interface `HasCount`, may be accessed
//
let restrictedCounter: @Counter{Count} <- counter
// Invalid: Only functionality of restriction `Count` is available,
// i.e. the read-only field `count`, but not the function `increment` of `Counter`
//
restrictedCounter.increment()
// Move the resource in variable `restrictedCounter` to a new variable `unrestrictedCounter`,
// again typed as `Counter`, i.e. all functionality of the counter is available
//
let unrestrictedCounter: @Counter <- restrictedCounter
// Valid: The variable `unrestrictedCounter` has type `Counter`,
// so all its functionality is available, including the function `increment`
//
unrestrictedCounter.increment()
// Declare another resource type named `Strings`
// which implements the resource interface `HasCount`
//
pub resource Strings: HasCount {
pub var count: Int
access(self) var strings: [String]
init() {
self.count = 0
self.strings = []
}
pub fun append(_ string: String) {
self.strings.append(string)
self.count = self.count + 1
}
}
// Invalid: The resource type `Strings` is not compatible
// with the restricted type `Counter{HasCount}`.
// Even though the resource `Strings` implements the resource interface `HasCount`,
// it is not compatible with `Counter`
//
let counter2: @Counter{HasCount} <- create Strings()Last updated