myaa
05/27/2020, 1:48 AMalso
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
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
Derek Peirce
05/27/2020, 4:06 AMdoIfNull { ... }
method, I doubt it's a common enough case to warrant anything in stdlib.Bornyls Deen
05/27/2020, 8:05 AMalso
for this but it doesn't look very nice to me.
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
val result = value.takeIf { it >= 0 }
if (result == null) {
println("Warning: negative value")
}
myaa
05/27/2020, 5:14 PMif (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