what's an idiomatic way of saying "if null, run th...
# announcements
m
what's an idiomatic way of saying "if null, run this and return null"? kind of like how
also
runs a function and then returns the original value, except that i only want to run the function if the original value is null i've got something like
Copy code
value.takeIf { it >= 0 } ?: run { println("Warning: negative value"); null }
except i'd like to avoid manually having to return null at the end of the
run
d
If you need this pattern frequently, you can add your own
doIfNull { ... }
method, I doubt it's a common enough case to warrant anything in stdlib.
b
I suppose you could use
also
for this but it doesn't look very nice to me.
Copy code
val result = value.takeIf { it >= 0 } ?: null.also { println("Warning: negative value") }
If chaining the statements together isn't required I'd probably just use a more traditional approach
Copy code
val result = value.takeIf { it >= 0 }
if (result == null) {
    println("Warning: negative value")
}
m
the thing is that this is for use as the return value of a short function, and defining a variable like that means having to add a bunch of other boilerplate (explicit return, explicit return type, braces) another idea i had was to use an if/else expression, but it's not really that different from what i had originally since i still need to manually specify the "null":
Copy code
if (value >= 0) value else { println("Warning"); null }
i guess i'll just have to deal with it/define an extension function if needed thanks for the suggestions