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. Therefore, there exists a syntactic variation of the "?
" operator that allows giving an explicit name to the variable.
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() ?=last
text.getDocument()?_.styles.findByName(styleName) ?=style
last.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.