In short expressions, the name "_
" is readable and appropriate. However, in larger constructs, it can become problematic and conflicting, especially if multiple "?
" operators are nested within each other.
Actually the ?
-operator expects its RHS operand to be a lambda expression. And for this case Argentum allows any expression to be implicitly convertible to lambda. Though nothing prevents us from put there the actual lambda definition which allows to explicitly define the name of the parameter instead of using the default `_
`.
In the shortest form the single-parameter lambda is defined as `name expression
.
produceSomeConditionalData() ? `data {
data.method(); // Using the name `data` instead of "_"
}
Let's consider a less abstract example:
fn applyStyleToLastParagraph(text TextBlock, styleName String) {
text.getLastParagraph() ?`lastParagraph
text.getDocument()?_.styles[styleName] ?`style
lastParagraph.forEach `span {
span.applyStyle(style)
}
}
This function checks if the text has a last paragraph and if the document exists and has a style with the specified name before applying the style to the paragraph. And all of this is done without introducing block-level variables that clutter the namespace and prolong the life of an object beyond necessity. Additionally, these variables are bound not to the optional value, but to the already unpacked value that has passed the check for being non-empty.