Skip to content
This repository was archived by the owner on Nov 10, 2018. It is now read-only.

Using return values

Tim Seckinger edited this page Jan 12, 2017 · 8 revisions

Return types

You can return various types of values from your script, and the result will be intelligently converted for substitution / completion.

"Normal" objects

Often, simply calculating some text to be inserted is all a script needs to do. Therefore, "normal" objects that have no special handling, such as Strings and Integers will be toStringed and inserted in the place of the template variable.

Examples (Groovy)

'asdf' // => asdf
-65.43e21 // => -6.543E+22
java.time.LocalDate.now() // => 2016-12-15
new Observable() // No useful toString() => Observable@1234abcd
null // null-safe => null

I/O

Readers and InputStreams will be fully read using the default charset to insert their text.

Examples (Groovy)

new StringReader('asdf') // => asdf
new ByteArrayInputStream([0x61, 0x73, 0x64, 0x66] as byte[]) // UTF-8 => asdf

Functions

A Supplier will be queried for a return value using Supplier.get().

Example (Groovy)

{ -> 'asdf' } as java.util.function.Supplier // => asdf

Optionals

An Optional will be unwrapped to get its value.

Examples (Groovy)

Optional.of('asdf') // => asdf
Optional.empty() // => empty

Collections

Returning a collection (or similar type, see below) triggers a completion popup offering all its values.
Each value is itself converted according as described on this page.
Nested collections are flattened.

The following collection-ish types are supported:

Examples (Groovy)

['a', 4] // Simple example => a, 4
[a: 'b', c: 'd'] // Map values => b, d
['a', new StringReader('b')] // Recursive conversion => a, b
['a', ['b', 'c']] // Flattening => a, b, c
['a', [abc: ['b', 'c'].stream(), xyz: new StringReader("d")]] // Recursive flattening and conversion => a, b, c, d
[] // Empty collection => null

Using System.out

If you want to print the text to be inserted instead of returning a string, you can simply print as normal and then return _out at the end.

Example (Groovy)

print 'ab'
println 'c'
print 'xyz'
return _out
/*
Result:
abc
xyz
*/

How does it work?

The script gets its own StringWriter bound to _out and the standard output System.out. The StringWriter buffers everything written to it and when it is converted as the script’s result as per <<"Normal" objects>>, its toString() returns the buffered text.

Tips

  • You can check the "Skip if defined" option in the "Edit template variables" dialog to skip the single-element completion popup.
    If you return a collection of size greater than 1 from your script, the popup will still be shown.

  • Also consider the template options available below the "Edit variables" button.