Browse Source

Docs and tests for painless lack of boxing for ?: and ?. (#21756)

NOTE: The result of `?.` and `?:` can't be assigned to primitives. So
`int[] someArray = null; int l = someArray?.length` and
`int s = params.size ?: 100` don't work. Do
`def someArray = null; def l = someArray?.length` and
`def s = params.size ?: 100` instead.

Relates to #21748
Nik Everett 9 years ago
parent
commit
434fa4bd26

+ 6 - 0
docs/reference/modules/scripting/painless-syntax.asciidoc

@@ -189,6 +189,12 @@ NOTE: Unlike Groovy, Painless' `?:` operator only coalesces `null`, not `false`
 or http://groovy-lang.org/semantics.html#Groovy-Truth[falsy] values. Strictly
 speaking Painless' `?:` is more like Kotlin's `?:` than Groovy's `?:`.
 
+NOTE: The result of `?.` and `?:` can't be assigned to primitives. So
+`int[] someArray = null; int l = someArray?.length` and
+`int s = params.size ?: 100` don't work. Do
+`def someArray = null; def l = someArray?.length` and
+`def s = params.size ?: 100` instead.
+
 
 [float]
 [[painless-control-flow]]

+ 4 - 0
modules/lang-painless/src/test/java/org/elasticsearch/painless/ElvisTests.java

@@ -37,6 +37,10 @@ public class ElvisTests extends ScriptTestCase {
         assertCannotReturnPrimitive("int i = params.a ?: 1; return i");
         assertCannotReturnPrimitive("Integer a = Integer.valueOf(1); int b = a ?: 2; return b");
         assertCannotReturnPrimitive("Integer a = Integer.valueOf(1); int b = a ?: Integer.valueOf(2); return b");
+        assertEquals(2, exec("int i = (params.a ?: Integer.valueOf(2)).intValue(); return i"));
+        assertEquals(1, exec("int i = (params.a ?: Integer.valueOf(2)).intValue(); return i", singletonMap("a", 1), true));
+        assertEquals(1, exec("Integer a = Integer.valueOf(1); int b = (a ?: Integer.valueOf(2)).intValue(); return b"));
+        assertEquals(2, exec("Integer a = null; int b = (a ?: Integer.valueOf(2)).intValue(); return b"));
 
         // Assigning to an object
         assertEquals(1, exec("Integer i = params.a ?: Integer.valueOf(1); return i"));