Multiple actions if null

Hello,
Say I have the following code:

var test = …
…
test?.let {
	print(test)
} ?: return null

Now, in addition to the null return value I would like to log a message, something similar to that:

test?.let {
	print(test)
} ?: {
	log.info("foo") 
	return null
}

How do I do it ? I can create a separate function that always return null, but it’s quite ugly

test?.let {
	print(test)
} ?: run { // ------------------- use run
	log.info("foo") 
	return null
}
2 Likes

Just a side note you could remove the “?: return null” in your first example:

var test = …
…
test?.let {
	print(test)
} ?: return null // <---- Unnecessary

That is only true if the next statement were return test, which is not a given

or better yet using also:

test?.let {
	print(test)
} ?: null.also { log.info("foo") }

I think I prefer run instead of null.also. It feels less hacky.

Actually in general I find it exactly the opposite. I find also or apply to be more clear. Right up front you say here is the value that this expression will have but here are some additional actions to perform. It is somewhat unusual to use it on null, but it is perfectly valid.

Well I guess it depends on the context. Because in the original example he wanted to return null I thought it was kind of a guard expression with some additional “error handling”. That’s why I would prefer run.

Well,there is a magic new construct totally exclusive to kotlin… It‘s called the ˋifˋ statement…

if (test == null) {
    log.info("foo")
    return null
}
print(test)

Usually simpler is better…
So I’d prefer this instead ob abusing ‘let’ or ‘run’.
Best regards, Daniel

4 Likes

@DanielR sometimes if is not feasible, specifically in situation where test is var and might change, but as a general saying I completely agree