Skip to content

Inline List, Maps and Arrays

tporcham edited this page Jan 30, 2019 · 1 revision

MVEL allows you to express Lists, Maps and Arrays using simple elegant syntax. Consider the following example:

['Bob' : new Person('Bob'), 'Michael' : new Person('Michael')]

This is functionally equivalent to the following code:

Map map = new HashMap();
map.put("Bob", new Person("Bob"));
map.put("Michael", new Person("Michael"));

This can be a very powerful way to express data structures inside of MVEL. You can use these constructs anywhere, even as a parameter to a method:

something.someMethod(['foo' : 'bar']);

Lists

Lists are expressed in the following format: [item1, item2, ...]
For example:

["Jim", "Bob", "Smith"]

Maps

Maps are expressed in the following format: [key1 : value1, key2: value2, ...] For example:

["Foo" : "Bar", "Bar" : "Foo"]

Arrays

Arrays are expressed in the following format: {item1, item2, ...}
For example:

{"Jim", "Bob", "Smith"}

Array Coercion

One important facet about inline arrays to understand is their special ability to be coerced to other array types. When you declare an inline array, it is untyped, but say for example you are passing to a method that accepts int[]. You simply can write your code as the following:

foo.someMethod({1,2,3,4});

In this case, MVEL will see that the target method accepts an int[] and automatically type the array as such.