SomonScriptDocsClasses and modules
Chapters 8-9 • Classes and modules

Classes and modules in SomonScript

Classes and modules help organize code in medium and large projects. Here we will see how to create a simple class and a module.

1. A simple example: a student class

First, let's create a simple class Донишҷӯ that has several properties and one method.

Student class

A simple class with a constructor and a method for printing data.

example.som
// Declaring the student class
синф Донишҷӯ {
  ном: сатр;
  синну_сол: рақам;

  конструктор(ном: сатр, синну_сол: рақам) {
    ин.ном = ном;
    ин.синну_сол = синну_сол;
  }

  // Method for printing data
  нишон_додан(): беджавоб {
    чоп.сабт("Донишҷӯ: " + ин.ном + ", синну сол: " + ин.синну_сол);
  }
}

// Creating and using an object of the class
тағ ахмад: Донишҷӯ = нав Донишҷӯ("Аҳмад", 20);
ахмад.нишон_додан();
terminal
somon run classes.som
Донишҷӯ: Аҳмад, синну сол: 20

2. A harder example: a class in a separate module

Every .som file is a module. In this example, the file models.som exports a class with содир, and the file main.som imports it with ворид.

Module with classes

Two files in one folder: models.som and main.som. Run the program with the command somon run main.som.

example.som
// file: models.som
содир синф Китоб {
  ном: сатр;
  муаллиф: сатр;

  конструктор(ном: сатр, муаллиф: сатр) {
    ин.ном = ном;
    ин.муаллиф = муаллиф;
  }

  нишон_додан(): беджавоб {
    чоп.сабт('"' + ин.ном + '" - ' + ин.муаллиф);
  }
}

// file: main.som
ворид { Китоб } аз "./models";

тағ китоб: Китоб = нав Китоб("SomonScript", "Гурӯҳи SomonScript");
китоб.нишон_додан();
terminal
somon run main.som
"SomonScript" - Гурӯҳи SomonScript

3. Exercises

These exercises help reinforce your understanding of classes and modules.

  1. Create a class Мошин with the properties ном (name), сол (year), ранги_мошин (car color) and the method нишон_додан().
  2. Create a module that exports two classes, Муаллим and Донишҷӯ, and use them in a separate file.
  3. Create a class Ҳисобкунак (Calculator) with methods for addition, subtraction, multiplication and division, and put it in a module.