View Javadoc
1   /*
2    * Copyright (c) Patrick Magauran 2018.
3    *   Licensed under the AGPLv3. All conditions of said license apply.
4    *       This file is part of ABOS.
5    *
6    *       ABOS is free software: you can redistribute it and/or modify
7    *       it under the terms of the GNU Affero General Public License as published by
8    *       the Free Software Foundation, either version 3 of the License, or
9    *       (at your option) any later version.
10   *
11   *       ABOS is distributed in the hope that it will be useful,
12   *       but WITHOUT ANY WARRANTY; without even the implied warranty of
13   *       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   *       GNU Affero General Public License for more details.
15   *
16   *       You should have received a copy of the GNU Affero General Public License
17   *       along with ABOS.  If not, see <http://www.gnu.org/licenses/>.
18   */
19  
20  package Utilities;
21  import java.util.Objects;
22  import java.util.function.Consumer;
23  import java.util.function.Supplier;
24  
25  public class Settable<T> {
26      private T val;
27      private T inval;
28      private Boolean set;
29  
30      public Settable(T val, T inval) {
31  
32          this.val = val;
33          this.inval = inval;
34          set = (!Objects.equals(val, inval));
35      }
36  
37      public Settable(T val) {
38          this.val = val;
39          this.inval = null;
40          set = false;
41      }
42  
43      public Settable() {
44          val = null;
45          this.inval = null;
46          set = false;
47      }
48  
49      public Boolean isSet() {
50          return set;
51      }
52  
53      public void set(T val) {
54          if (!(val == null)) {
55              this.val = val;
56              set = (!Objects.equals(val, inval));
57          } else {
58              set = false;
59          }
60  
61      }
62  
63      public void setIfNot(T val) {
64          if (!set) {
65              this.val = val;
66              set = true;
67          }
68      }
69  
70      public T get() {
71          return isSet() ? val : inval;
72      }
73  
74      public void clear() {
75          this.val = null;
76          set = false;
77      }
78  
79      public void ifSet(Consumer<? super T> consumer) {
80          if (this.set && !Objects.equals(val, inval)) {
81              consumer.accept(this.val);
82          }
83      }
84  
85      public T orElseGetAndSet(Supplier<? extends T> var1) {
86          if (!(this.set && !Objects.equals(val, inval))) {
87              this.val = var1.get();
88          }
89          return this.val;
90      }
91  
92      public T orElseGet(Supplier<? extends T> var1) {
93          return (this.set && !Objects.equals(val, inval)) ? this.val : var1.get();
94      }
95  
96      public String toString() {
97          return val.toString();
98      }
99  }
100