From 434fa4bd263f9869fb81ba3f6a6a4bb82d4fd22b Mon Sep 17 00:00:00 2001 From: Nik Everett Date: Wed, 23 Nov 2016 14:33:32 -0500 Subject: [PATCH] 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 --- docs/reference/modules/scripting/painless-syntax.asciidoc | 6 ++++++ .../test/java/org/elasticsearch/painless/ElvisTests.java | 4 ++++ 2 files changed, 10 insertions(+) diff --git a/docs/reference/modules/scripting/painless-syntax.asciidoc b/docs/reference/modules/scripting/painless-syntax.asciidoc index d89e79fc5d4..10d6d501412 100644 --- a/docs/reference/modules/scripting/painless-syntax.asciidoc +++ b/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]] diff --git a/modules/lang-painless/src/test/java/org/elasticsearch/painless/ElvisTests.java b/modules/lang-painless/src/test/java/org/elasticsearch/painless/ElvisTests.java index 44859852240..fc760c479a1 100644 --- a/modules/lang-painless/src/test/java/org/elasticsearch/painless/ElvisTests.java +++ b/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"));