Ryan
Ryan

Reputation: 427

Methods that work for both mutable and immutable objects in D

I'm trying to write an access method for a class in D that I want to work for both mutable and immutable instances.

public immutable(double[]) getInputs(uint i)immutable{
  return this.data[i];
}
public double[] getInputs(uint i){
  return this.data[i];
}

I keep getting compiler errors unless I make both these versions that do (almost) the exact same thing.

Since I'm not changing any state, is there any way to use a single method that operates both on mutable and immutable instances?

Upvotes: 4

Views: 109

Answers (1)

Vladimir Panteleev
Vladimir Panteleev

Reputation: 25187

D has inout for this:

public inout(double[]) getInputs(uint i) inout
{
    return this.data[i];
}

This will work when the object (this) is const, immutable, or neither (mutable). The constness of the returned value will be the same as this.

See the documentation for inout functions for more information.

Upvotes: 4

Related Questions