2

Reading through the Vala docs, I see there's a shorthand for defining a property:

public class Person : Object { public int age { get; set; default = 32; } } 

I tried to define a read-only variable by removing set; from the list, but I get a compilation error that the getter must be defined. I've resorted to using the longhand form:

public class Person : Object { private int _age = 32; public int age { get { return _age; } } } 

Is there a way to use the shorthand notation to with defining a setter?

1 Answer 1

8

No. If you could just do public int age { get; }, where would the value come from?

What you probably want is:

public class Person : Object { public int age { get; private set; } } 
Sign up to request clarification or add additional context in comments.

3 Comments

I set a default value like public int age { get; default = 32; }. My assumption was that Vala would be smart and set the initial value but never expose a setter method.
But you're also going to want a way to set the property, otherwise public const int AGE = 32; would make more sense. You can use a getter with an implementation without a setter because you could be computing the value (e.g., from an age_in_days field) or getting it from anywhere else. However, with an automatic getter I really can't imagine a situation where it makes sense.
In that case, the value could come from bypassing the (non-existing) setter by letting the owning class directly access the backing variable. This is not how it works in Vala, but I would prefer it that way. While working, private set looks a bit redundant to me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.