Skip to content

Commit

Permalink
Add convenience value builder
Browse files Browse the repository at this point in the history
  • Loading branch information
trask committed Dec 4, 2024
1 parent 6556acf commit 59862e4
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 0 deletions.
5 changes: 5 additions & 0 deletions api/all/src/main/java/io/opentelemetry/api/common/Value.java
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,11 @@ static Value<List<KeyValue>> of(Map<String, Value<?>> value) {
return KeyValueList.createFromMap(value);
}

/** Returns a new {@link ValueBuilder} instance for creating an arbitrary {@link Value}. */
static ValueBuilder builder() {
return new ValueBuilderImpl();
}

/** Returns the type of this {@link Value}. Useful for building switch statements. */
ValueType getType();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.common;

public interface ValueBuilder {

default ValueBuilder put(String key, String value) {
put(key, Value.of(value));
return this;
}

default ValueBuilder put(String key, long value) {
put(key, Value.of(value));
return this;
}

default ValueBuilder put(String key, double value) {
put(key, Value.of(value));
return this;
}

default ValueBuilder put(String key, boolean value) {
put(key, Value.of(value));
return this;
}

ValueBuilder put(String key, Value<?> value);

Value<?> build();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.common;

import java.util.ArrayList;
import java.util.List;

class ValueBuilderImpl implements ValueBuilder {

private final List<KeyValue> keyValues = new ArrayList<>();

@Override
public ValueBuilder put(String key, Value<?> value) {
keyValues.add(KeyValue.of(key, value));
return this;
}

@Override
public Value<?> build() {
return Value.of(keyValues.toArray(new KeyValue[0]));
}
}

0 comments on commit 59862e4

Please sign in to comment.