All these constructs will perform about the same. (The two functions are inlined, so the actual compiled code will be almost identical. But even they weren’t, the JVM is very good at optimising such things, and even in a tight loop I wouldn’t expect this sort of thing to make any practical difference.) So this is more a matter of readability.
The simple ‘if’ construct is short, simple, readable, and obvious to anyone who’s used just about any programming language in the last half-century.
Your notnull function is ingenious, but is arguably harder to read, and saves only four characters. (You could rename it to ifNotNull, but then it would save only two characters…)
The ?.let construct is fairly common in Kotlin, but mainly for cases when the value will be used inside the block (either as it, or given an explicit name); that’s handy when the value is a big expression you don’t want to duplicate, or it’s mutable and so the compiler can’t smart-cast it to non-nullable without having its value captured.
If none of that applies, I’d stick with the simple if (…).
Off course if is simple but its not very function style for the purpose kotlin has so many scope functions and other bells what Java does not offer.
When programmer wants to write a block of code when some variable is not null, it is not straight to put if in if and then add the block rather with this function its intuitive to just add to the flow and its also more easy to read, like
var.ifNotNull {
}
Kotlin should have some inbuilt syntax for this purpose as its very common like
var?: {
}
if (thing != null) {
// do something with the thing
}
Why would we need to overcomplicate things?
If you really need a functional way of doing it, there is always the option of using let, so I really don’t see any point in adding anything to the language here, even before applying the -100 points rule.
…then you just need to note that ifis functional: in Kotlin, an if…else block returns an expression. (That’s why Kotlin has no ?…: operator: if…else does the same job.)
Some would say a much clearer and more readable manner.
Could the extra complexity of adding a new operator to the language (one which doesn’t fit the consistent meaning of ? in all other operators, and could well introduce syntactic ambiguities, as well as the potential for abuse, and confusion over multiple ways to do the same thing) really be justified by saving only 4 characters?