Unlike the basic values, getting values from lists is slightly more involved, as multiple values are involved. The main getters for lists are getList(Function<Object, T>):List<T>
, getList(Function<Object, T>, List<T>):List<T>
, getList(TypeToken<T>):List<T>
, getList(TypeToken<T>, List<T>):List<T>
.
For the purpose of teaching the following sample will be used be used:
{
"modules" : {
"blockCheats" : {
"enabled" : true,
"counters" : [1,2,3,4, "hello", 1.22]
}
}
}
Where for basic values you can just do:
root.getNode("modules", "blockCheats", "enabled").getBoolean(false);
This cannot be done for lists. Instead you have do something like this:
root.getNode("modules", "counters").getList(new Function<Object, Integer>(
@Override
public Integer apply(Object input) {
if (input instanceof String) {
return (Integer) input;
}
return null;
}
)
The above code will return a list containing [1,2,3,4]
. This can also shortened down using lambda expression:
root.getNode("modules").getList(input -> return input instanceof Integer ? (Integer) input : null);
However you may notice that running same checks again and again may be inefficient and only potentially cause errors. Configurate provides a handy utility to handle that for you. The above example can be replaced by:
import ninja.leaping.configurate.Types;
root.getNode("modules","counters").getList(new Function<Object, Integer> {
@Override
public Integer apply(Object input) {
return Types.asInt(input)
}
}
Or simply:
import ninja.leaping.configurate.Types;
root.getNode("modules", "counters").getList(Types::asInt);
Repetition of "involved" in first paragraph.
Add an explanation of why "you have to do something like this". Ex: Lists are stored as List and each element must be converted to the desired type.
For the Types.asInt() example, no need to provide another example of an anonymous class, as there already is an example above (lambdas are preferred). Or alternatively, the lambda example for the first impl. could be removed, and the second anon. class would be a continuation/revision of the previous one.