Skip to content

Classes

A class is a user defined type that bundles data (variable/field) and functionality (function/method) together.

class User {
var active = false
fn activate() {
require(!active, "already active")
active = true
}
}

There’re variables and functions in class body. The variables are called fields. The functions are called methods.

We can create an instance of the class and access the field and method:

// Create an instance
val user = User()
// Initially inactive
print("Active: " + user.active)
// Call method
user.activate()
// Check again
print("Active: " + user.active)

Constructor parameters allow the class to take inputs when instances are created.

Let’s add a “name” constructor parameter to User:

class User(
var name: string
) {
var active = false
fn activate() {
require(!active, "already active")
active = true
}
}

We added a constructor parameter name, a field name and initialize the field with the parameter.

Let’s create an instance with a name:

val user = User("someone")
print(user.name)

The pattern of creating a constructor parameter and a field with the same name and use the parameter to initialize the field is a very common pattern. To reduce boilerplate, you can declare the constructor parameter and field in a single line by adding the var or val keyword to the parameter:

class User(
var name: string
) {
var active = false
fn activate() {
require(!active, "already active")
active = true
}
}

Inner class is a class declared inside another class.

class Order {
class Item(
var product: Product
)
}

To instantiate an inner class, you first need to create an instance of the outer class and use the outInstance.InnerClass() syntax to create the instance of the inner class.

The following example shows how to create an order item:

val order = Order()
val item = order.Item(product)

The outer instance and the inner instance form a parent-child relation. We all the outer instance the parent object of the inner instance, and call the inner instance child object of the outer instance. Since inner instance can also have child objects of their own, it parent-child relations form a hieranchy. We call the entire tree an aggregate.

Inner classes has signifcant implication about data storage: The entire aggregate is stored as a single unit.