2

I would like a read-only instance property in an Apex class, to prevent it ever being changed after instantiation. I can't work out how to initialise it.

I would like to be able to write something like the following:

public class Test {
    private Integer MyInt {get;}

    public Test( Integer i ) {
        // How to initialise MyInt?  This causes a compiler error:
        MyInt = i;
    }

    public void MyIntention() {
        // My intention is to be able to read MyInt:
        Integer result = 2 * MyInt;

        // but MyInt is write-protected, so this should cause a compiler error:
        MyInt = 22;
    }
}

Is it possible in Apex?

1
  • If you get an error message, please include it verbatim...
    – Adrian Larson
    Commented Nov 1, 2017 at 12:36

1 Answer 1

2

You still need to write a setter. Please also note that if your variable is private, so is the getter. If you want to make the property only writable within the class, here is how I would do it:

public with sharing class MyClass
{
    public Integer myProperty { get; private set; }
    public MyClass(Integer value)
    {
        myProperty = value;
    }
}

If you want to make the property only writable from your constructor, you can instead use the final keyword. Note that attempts at reassignment will cause a run-time error, not compile-time.

public with sharing class MyClass
{
    final Integer property;
    public MyClass(Integer property) { this.property = property; }
    public void increment(Integer value)
    {
        property += value; // will cause run-time error
    }
}

Using the final Keyword

You can use the final keyword to modify variables.

  • Final variables can only be assigned a value once, either when you declare a variable or inside a constructor. You must assign a value to it in one of these two places.
  • Static final variables can be changed in static initialization code or where defined.
  • Member final variables can be changed in initialization code blocks, constructors, or with other variable declarations.
  • To define a constant, mark a variable as both static and final.
  • Non-final static variables are used to communicate state at the class level (such as state between triggers). However, they are not shared across requests.
  • Methods and classes are final by default. You cannot use the final keyword in the declaration of a class or method. This means they cannot be overridden. Use the virtual keyword if you need to override a method or class.
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .