Skip to content

3) Classes

rookieCookies edited this page Aug 19, 2022 · 1 revision

Classes are objects that can contain data and functions

Declaring Classes

The syntax for declaring a new class is simple

Syntax: class Example { ... }

Here's an example of a class

class Hi {
    var x = 3
    var y = 2
    var z = 1

    fn hi() {
        println(x)
        println(y)
        println(z)
    }
}

Instancing Classes

Now instancing a class is different than declaring a class
When you create a class you instantiate an already declared class and use it.
You can think of class declarations as a blueprint for the value you can instance later on

... // Class declaration above

var x = new Example()

This creates a new object from the class declaration we defined above and calls its constructor which we will get to now
If the class constructor requires arguments you'd have to enter the arguments inside the parenthesis like it was a function

... // The class declaration above

var x = new Example("hello", 12, 43.0)

Constructors

Unlike other scopes, classes don't allow many statements like updating variables

class Example {
    var x = 5 // Variable declarations are fine

    x *= 5 // Will throw an error
}

But sometimes you want to instantiate some code and declare the variables in a mode dynamic way
That's where constructors come in! Creating constructors are as simple as creating a new function!

class Example {
    var x = 5

    fn constructor() {
        x *= 5
    }
}

Since a constructor is just a function call you can use arguments as you would

class Example {
    var x : int

    fn constructor(multiply_amount : int) {
        x *= multiply_amount
    }
}

Much better!
One thing to note is that the constructor can't return anything, if it does, the return data will be discarded and after the constructor is called it can't be called again

Accessing inside a class instance

Now that we've got a class instance we can actually call methods or access variables in it!

class Greet {
    var name : str 
    fn constructor(greet_name : str) {
        name = greet_name
    }

    fn say_hi() {
        println("Hello " + name "!")
    }
}

Let's use this class as an example

var greet = new Greet("Bob") // Create a class instance
greet.say_hi() // This will print out "Hello Bob!"
greet.name = "Jake" // We update the name variable of the class instance
greet.say_hi() // This will print out "Hello Jake!" since we have updated the name variable

Classes might seem simple, but they allow for much more complex things to happen. Don't underestimate their power!

Clone this wiki locally