Skip to content

Commit

Permalink
Add single type conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
Rubenicos committed Aug 23, 2023
1 parent 1ec1fcc commit 94e884d
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
6 changes: 4 additions & 2 deletions docs/default/feature/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,11 @@ Take in count the multiple-type conversion doesn't do "magic" to convert types,

:::

:::caution Current limitations
:::tip Single type conversion

The `OptionalType` instance provide a single object to collection or array conversion, but it doesn't convert collections or arrays into single objects.
If you want the `OptionalType` instance as single object just wrap it with `OptionalType#single()` method, if the current type is a collection or array the first value will be used **recursively**.

For only "the first value" use the method `OptionalType#first()` instead.

:::

Expand Down
6 changes: 4 additions & 2 deletions docs/es/feature/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,11 @@ Tomar en cuenta que la conversión de múltiples objetos no hace "magia" para co

:::

:::caution Limitaciones actuales
:::tip Conversión de objeto único

La instancia de `OptionalType` tiene conversión de objetos únicos a objetos múltiples como colecciones o array, pero no puede convertir colecciones y arrays en objetos únicos.
Si quieres que la instancia de `OptionalType` sea un objeto único solamente utiliza el método `OptionalType#single()`, si el tipo de objeto actual es una colección o array el primer valor será utilizado **de manera recursiva**.

Para tener solo "el primer valor" utiliza en cambio el método `OptionalType#first()`.

:::

Expand Down
32 changes: 32 additions & 0 deletions src/main/java/com/saicone/rtag/util/OptionalType.java
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,38 @@ public boolean isNotInstance(Class<?> clazz) {
return !isInstance(clazz);
}

/**
* Get the first value.<br>
* This method extract the first value if the current object is a collection or array.
*
* @return An OptionalType with object value.
*/
public OptionalType first() {
if (isIterable()) {
for (Object o : this) {
return OptionalType.of(o);
}
return OptionalType.EMPTY;
}
return this;
}

/**
* Get actual value as single object<br>
* This method make a recursively extract from the first value if the current object is a collection or array.
*
* @return An OptionalType with object value.
*/
public OptionalType single() {
if (isIterable()) {
for (Object o : this) {
return OptionalType.of(o).single();
}
return OptionalType.EMPTY;
}
return this;
}

/**
* Get actual value converted to required type.
*
Expand Down

0 comments on commit 94e884d

Please sign in to comment.