a fork of EvalEx by ezylang with a handful of breaking changes
1---
2layout: default
3title: Data Access
4parent: Customization
5nav_order: 5
6---
7
8## Data Access
9
10By default, EvalEx has its own storage for variable values, the _MapBasedDataAccessor_.
11It stores and retrieves the variables in a case-insensitive _TreeMap_.
12A separate instance of the _MapBasedDataAccessor_ will be created through the default configured
13supplier for each new Expression, separating the storage for each expression instance.
14
15You can easily define your own data access interface, by defining a class that implements the
16_DataAccessorInterface_:
17
18```java
19public interface DataAccessorIfc {
20
21 /**
22 * Retrieves a data value.
23 *
24 * @param variable The variable name, e.g. a variable or constant name.
25 * @return The data value, or <code>null</code> if not found.
26 */
27 EvaluationValue getData(String variable);
28
29 /**
30 * Sets a data value.
31 *
32 * @param variable The variable name, e.g. a variable or constant name.
33 * @param value The value to set.
34 */
35 void setData(String variable, EvaluationValue value);
36}
37```
38
39Only two methods need to be implemented:
40
41- getData(String variable) - should return a value for a variable name.
42- setData(String variable, EvaluationValue value) - set a variable value.
43
44The _setData()_ method is only called when a variable is added to the expression, e.g. using the
45_with()_ method. You may leave the implementation empty, if you do want to support this.
46
47> NOTE: The variable names that are passed to the methods are case-sensitive, just like they were
48> entered in the expression.
49
50The custom data accessor can then be specified in the expression configuration:
51
52```java
53ExpressionConfiguration configuration = ExpressionConfiguration.builder()
54 .dataAccessorSupplier(MyCustomDataAccessor::new)
55 .build();
56
57Expression expression = new Expression("2.128 + a", configuration);
58```
59
60The example here creates a new instance of the _MyCustomDataAccessor_ for each new instance of an
61expression. But you could also share an instance for all expressions:
62
63```java
64final MyCustomDataAccessor customAccessor = new MyCustomDataAccessor();
65ExpressionConfiguration configuration = ExpressionConfiguration.builder()
66 .dataAccessorSupplier(() -> customAccessor)
67 .build();
68
69Expression expression = new Expression("2.128 + a", configuration);
70```