A Quick Introduction to Virgil - Components

This is part of a basic introduction to programming in Virgil and gives an overview of the language, its syntax, and its structures. This page focuses on declaring and using components, which are modules of related global methods and fields.

Overview

Virgil provides components as a way of declaring and scoping methods and fields of related functionality. A component has a single instantiate and thus exists "only once" in the program. Inside of a component, the methods and fields can be accessed through their names, but outside of the component, its methods and fields must be refered to through the name of the component.

Fields

component A {
    field size: int;
    field name: char[] = "MyName";
    method test() { size = 0; }
}
component B {
    method main() { A.size = 1; }
}

Fields are locations in memory that can store values. Because Virgil is a statically typed language, each field declaration must be given an explicit type, using a similar syntax to declaring local variables. A field declaration begins with the keyword field, followed by the name of the field (which must be a valid identifier), then a colon :, then the declared type, and then an optional expression to initialize the field.

In the example on the right, the component A declares a size field which is accessed from within the test() method in A and the main() method in B. It also declares a name field, which is initialized to the value "MyName".

Methods

component A {
    method run() { ... }
    method test() { run(); }
}
component B {
    method main() { A.run(); }
}

Methods can be declared inside a component using the syntax explained in the methods page. When a method is declared inside of a component, it has access to all of the component's members through their names. Access to the declared method from outside the declared component requires using the name of the component as a prefix.

In the example on the right, the component A declares a run() method which is accessed from within the test() method in A and the main() method in B.

Private Members

component A {
    private method internal() { ... }
}
component B {
    method test() {
        A.internal(); // ERROR
    }
}

Methods and fields within a component can be declared to be private, which makes them accessible only within the component. This provides a way to hide internal implementation details and protect the implementation of a component from outside disturbance. When a member is declared private, any attempt to access the member from outside of the component will result in a compile-time error. It is typically a good practice to declare fields of components private to prevent their modification from outside the component.

Go back to the tutorial.