I am using Spring expression version 4.3.2.RELEASE It seems we cannot use the Elvis operator for any other types than String and Boolean.
For example, the following will thrown an error: field ?: 2 > 0
If field = 1 we get java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Boolean
If field is null: then Elvis works correctly and use the value 2.
Can we work around this? is it a defect in SpEL?
thanks,
Sebastien
Elvis operator is shorthand notation for ternary operator, used in case of nullability check.
Its syntax is:
someField?:somevalue
where, someField can be of any type. Above expression will return value of someField (e.g. Integer)
, if it's not null
else it will return someValue
. someValue must be of same type as someField (Integer)
.
So, This is not a limitation of SPel. It is the specific usage of operator.
In your example, field
is an integer so, resolved value must also be of integer type. But, you are doing 2>0
that resolves to boolean type, which is not valid in this case.
What you can do is (field?: 2) > 0
, if it is what you are trying to achieve.
I hope, it clarifies.