Skip to content

Commit

Permalink
Use a proper setter to define blackboard keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Yeregorix committed Aug 28, 2024
1 parent 0d64d1a commit 6dd0fb4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,21 @@
import org.spongepowered.plugin.Environment;

import java.util.Optional;
import java.util.function.Supplier;

/**
* An entity that stores various properties for an {@link Environment environment}
*/
public interface Blackboard {

/**
* Retrieves a value by {@link Key key} or from the {@link Supplier default value}.
* Sets a value by {@link Key key}.
*
* @param key The key
* @param defaultValue The default value
* @param value The value
* @param <V> The value type
* @return The value
* @throws IllegalStateException if the key has already a corresponding value
*/
<V> V getOrCreate(final Key<V> key, final Supplier<? super V> defaultValue);
<V> void set(final Key<V> key, final V value);

/**
* @param key The key
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,23 @@
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;

public final class StandardBlackboard implements Blackboard {

private final Map<Key<Object>, Object> values;
private final Map<Key<?>, Object> values;

public StandardBlackboard() {
this.values = new HashMap<>();
}

@SuppressWarnings("unchecked")
@Override
public <V> V getOrCreate(final Key<V> key, final Supplier<? super V> defaultValue) {
public <V> void set(final Key<V> key, final V value) {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(defaultValue, "defaultValue");

return key.clazz().cast(this.values.computeIfAbsent((Key<Object>) key, k -> defaultValue.get()));
Objects.requireNonNull(value, "value");
if (this.values.containsKey(key)) {
throw new IllegalStateException(String.format("Key '%s' already has a value!", key.name()));
}
this.values.put(key, value);
}

@Override
Expand Down

0 comments on commit 6dd0fb4

Please sign in to comment.