Sage-Code Laboratory
index<--

Nim Objects

Nim has Classes, Objects and methods. A method in Nim is a function that is associated with an object. It can be defined with the "proc" keyword.

Objects are created with the "type" statement. For example, the following code creates an object of type "Person":


type Person = object
    name: string
    age: int

Methods

Objects can have methods, which are defined with the "proc" keyword. For example, the following code defines a method called "sayHello" that takes one parameter of type "Person":


proc sayHello(p: Person): string =
    return "Hello, " + p.name

Objects can also inherit from other objects. For example, the following code inherits the "Person" object from the "Animal" object:


type Human = Person of Animal

Inheritance

This means that a "Human" object has all of the properties and methods of a "Person" object, plus any additional properties and methods that are defined in the "Animal" object.

Classes are a way of organizing objects into groups. For example, the following code defines a class called "Mammals" that contains two objects, a "Human" and a "Dog":


class Mammals = object
    Humans: Human
    Dogs: Dog

Classes can also have methods. For example, the following code defines a method called "sayHello" that takes one parameter of type "Mammals":


proc sayHello(m: Mammals): string =
    return "Hello, " + m.Human.name + " and " + m.Dogs.name

In Nim, you can extend a class using the inherits keyword followed by the name of the class you want to inherit from. Here is the basic syntax:


type
  MyBaseClass = object
    # define your base class members here

  MyDerivedClass = object of MyBaseClass
    # define your derived class members here

In this example, we defined a base class MyBaseClass with some members. Then, we created a derived class MyDerivedClass using the of keyword after the class name and then the name of the class we want to inherit from (MyBaseClass).


type
  MyBaseClass = object
    name: string

  MyDerivedClass = object of MyBaseClass
    age: int

proc introduce(self: MyDerivedClass): string =
  result = "My name is " & self.name & " and I am " & $self.age & " years old."

var person = MyDerivedClass(name: "Alice", age: 30)
echo person.introduce()

MyDerivedClass inherits all the members of MyBaseClass, and we can add additional members to it as needed. For instance, here's an extended example:


Read next: Modules