Search code examples
linuxoopvala

Vala files import


I have a problem when work with properties in separated files in Vala Language

The Main.vala file is

using Teste;
using Cagado;

static int main(string[] args)
{   
   GUI gui = new GUI();
   stdout.printf("%d\n", gui.idade);
   return 0;
}

The HelloVala.vala is:

namespace Teste
{
    public class Person : Object
    {
        private int _age = 32;

        public int age
        {
            get { return _age; }
            set { _age = value; }
        }
    }
}

The Cagado.vala is:

using Teste;

namespace Cagado
{
    public class GUI : Object
    {
        Person _person = new Person();
        _person.age = 35;
        private int _idade;

        public int idade
        {
            get { return _idade; }
            set { _idade = value; }
        }
    }
}

When i compile this code, the compile gives me the message error:

Cagado.vala:9.15-9.15: error: syntax error, expected identifier
    _person.age = 35;
                ^

I program in C# and this not happened in C# oriented object system. Someone could explain this?


Solution

  • The problem is this:

    public class GUI : Object
    {
        Person _person = new Person();
        _person.age = 35; // <--
        ...
    

    You can't put arbitrary code inside of the class itself, only declarations. What you need to do is something like

    public class GUI : Objects
    {
        Person _person = new Person();
        construct {
            _person.age = 35;
        }
    

    You could also modify add a constructor to the Person class:

    namespace Teste
    {
        public class Person : Object
        {
            private int _age = 32;
    
            public int age
            {
                get { return _age; }
                set { _age = value; }
            }
    
            public Person(int age) {
                GLib.Object (age: age);
            }
        }
    }
    

    Then do

    public class GUI : Object
    {
        Person _person = new Person(35);