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
This commit is contained in:
Nik Everett 2016-11-23 14:33:32 -05:00 committed by GitHub
parent 49e1ca249a
commit 434fa4bd26
2 changed files with 10 additions and 0 deletions

View File

@ -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]]

View File

@ -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"));