Reading the fields
Accessing a property (field) of a modddel differs depending on whether it's a "member" or a "dependency".
Let's take as an example a Book
modddel :
Reading dependency fields
You can access "dependency" field from both the sealed class (Book
) and the union-cases.
In our example : Let's suppose Book
has a dependency parameter availabilityService
that checks whether a book is available.
Reading member fields
By default, a modddel hides its "member" fields inside its union-cases, so you can only access them after using a pattern matching method (map, mapValidity...).
In our example : Book
has two member parameters, id
and title
.
As you can see, you must use pattern matching to access the members of the modddel. This is so that you address all cases, and failures never go unnoticed by you the developer.
The @withGetter
annotation
@withGetter
annotationSometimes you may want to have a direct getter for a member parameter. For this, you can use the @withGetter
annotation.
For example, let's say you want to have a direct getter for the id
member parameter. First, annotate it with @withGetter
:
Now you can directly access the id
field :
It is advised to use @withGetter
sparingly, because it allows direct access to a member parameter, no matter if the modddel is valid or not. This can defeat the purpose of using a modddel, since you will be able to manipulate data that can be either valid or invalid in one place.
However, there are legitimate use cases where it is very useful. For example, if a member parameter is unrelated to the validity of the modddel (like in the case of the id
field in our Book
example), using @withGetter
is a good choice as it makes it easily accessible.