Multiple actions if null


#1

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


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

#3

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

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

#4

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


#5

or better yet using also:

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

#6

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


#7

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.


#8

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.


#9

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


#10

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