Created
April 20, 2016 23:25
-
-
Save kinggoesgaming/aee35220918b8371bd7d16239d3132bf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
List Values | |
~~~~~~~~~~~ | |
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: | |
.. code-block:: json | |
{ | |
"modules" : { | |
"blockCheats" : { | |
"enabled" : true | |
"counters" : [1,2,3,4, "hello", 1.22] | |
} | |
} | |
} | |
Where for basic values you can just do: | |
.. code-block:: java | |
root.getNode("modules", "blockCheats", "enabled").getBoolean(false); | |
This cannot be done for lists. Instead you have do something like this: | |
.. code-block:: java | |
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: | |
.. code-block:: java | |
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: | |
.. code-block:: java | |
import ninja.leaping.configurate.Types; | |
root.getNode("modules").getList(new Function<Object, Integer> { | |
@Override | |
public Integer apply(Object input) { | |
return Types.asInt(input) | |
} | |
} | |
Or simply: | |
.. code-block:: java | |
import ninja.leaping.configurate.Types; | |
root.getNode("modules").getList(Types::asInt); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment