diff --git a/rascal-lsp/src/main/java/org/rascalmpl/vscode/lsp/BaseWorkspaceService.java b/rascal-lsp/src/main/java/org/rascalmpl/vscode/lsp/BaseWorkspaceService.java index 75afbb69a..fee26a870 100644 --- a/rascal-lsp/src/main/java/org/rascalmpl/vscode/lsp/BaseWorkspaceService.java +++ b/rascal-lsp/src/main/java/org/rascalmpl/vscode/lsp/BaseWorkspaceService.java @@ -84,11 +84,7 @@ public void initialize(ClientCapabilities clientCap, @Nullable List boolean has(@Nullable A a, Function getFunc return get(get(a, getFunc1, null), getFunc2, defaultVal); } + /** + * Get a value from an object. If it was not set yet (i.e. `null`), initialize and set it before returning. + * @param The type of the containing object. + * @param The type of the value to get. + * @param container The containing object. + * @param getter The value getter. + * @param setter The value setter. Only called if the value is not initialized yet. + * @param initializer The value initializer (e.g. a constructor). Only called if the value is not initialized yet. + * @return The gotten value, or the initialized value if was not initialized yet. + */ + public static T ensureNonNullAndGet(C container, Function getter, BiConsumer setter, Supplier initializer) { + var t = getter.apply(container); + if (t == null) { + t = initializer.get(); + setter.accept(container, t); + assert getter.apply(container) != null : "Setter should set same value as getter gets"; + } + return t; + } + }