Idiomatic way to return if not null in Kotlin - kotlin

I am looking for an idiomatic way to return if not null a variable in Kotlin. For example, I would like something such as:
for (item in list) {
getNullableValue(item).? let {
return it
}
}
But it's not possible to return inside a let block in Kotlin.
Is there a good way to do this without having to do this:
for (item in list) {
val nullableValue = getNullableValue(item)
if (nullableValue != null) {
return nullableValue
}
}

Not sure if this would be called idiomatic, but you could do this:
val nullableValue = list.find { it != null }
if (nullableValue != null) {
return nullableValue
}
Edit:
Based on s1m0nw1's answer, you can probably reduce it to this:
list.find { it != null }?.let {
return it
}

It is possible to return from let, as you can read in the documentation:
The return-expression returns from the nearest enclosing function, i.e. foo. (Note that such non-local returns are supported only for lambda expressions passed to inline functions.)
let() is an inline function and therefore you automatically return from the enclosing function whenever you do return within let, like in this example:
fun foo() {
ints.forEach {
if (it == 0) return // nonlocal return from inside lambda directly to the caller of foo()
print(it)
}
}
To modify the behavior, "labels" can be used:
fun foo() {
ints.forEach lit# {
if (it == 0) return#lit
print(it)
}
}

The "right" idiomatic way of doing this is using the "first" method.
Example:
val x = listOf<Int?>(null, null, 3, null, 8).first { it != null }
His specific example would be
return list.first {getNullableValue(it) != null}

It could be something like:
for (item in list) {
getNullableValue(item)?.also {
return it
}
}
I am assuming the external loop is needed. If that is not the case, Ryba suggested solution should work.

Related

Kotlin ? vs ?.let {}

Consider this nice utility extension function i wanted to use :
inline infix fun <T> T?.otherwise(other: () -> Unit): T? {
if (this != null) return this
other()
return null
}
It could be very useful for logging stuff when expressions evaluated to null for example:
val x: Any? = null
x?.let { doSomeStuff() } otherwise {Log.d(TAG,"Otherwise happened")}
but I see that it wont work for :
val x: Any? = null
x?.otherwise {Log.d(TAG,"Otherwise happened")}
see here for running example
Well when thinking about it i guess that makes sense that if x is null the ? makes the postfix not be executed, but i dont understand why the let in the first example is any different?
Is it possible to fix the utility to be more robust and work without having to have let in the chain?
First, you can simplify the implementation:
inline infix fun <T> T?.otherwise(other: () -> Unit): T? {
if (this == null) { other() }
return this
}
Or
inline infix fun <T> T?.otherwise(other: () -> Unit): T? =
also { if (it == null) other() }
When you do this:
null?.otherwise { println("Otherwise happened") }
?. means "execute if not null", so otherwise is not executed.
What you need to write is:
null otherwise { println("Otherwise happened") }
Note this is very similar to the ?: operator (as Vadik pointed out in the comments):
null ?: println("Otherwise happened")
The difference is that otherwise always returns the value on the left (the same as also), but ?: returns the value on the right when the value on the left is null.
In my opinion, otherwise is confusing, especially as it always returns the left value despite the name. You would be better to use the ?: operator. Or perhaps rename it to something like alsoIfNull.
The let example executes because, when you don't utilize the infix feature, it looks like this:
x?.let {}.otherwise {println("1")}
Notice that it's not ?.otherwise; therefore, it always executes.
So to use otherwise without let, you can omit the ?.
x.otherwise { ... }
x?.let { doSomeStuff() }.otherwise {Log.d(TAG,"Otherwise happened")}
// ⬇️
val value = if (x != null) {
doSomeStuff()
} else {
null
}
value.otherwise {Log.d(TAG,"Otherwise happened")}
x?.otherwise { Log.d(TAG,"Otherwise happened") }
// ⬇️
if (x != null) {
otherwise { Log.d(TAG,"Otherwise happened") }
} else {
null
}
?. means if the value is not null then execute the method and return the result otherwise return null

kotlin: If value is null then exit, else use that value as not nullable

Essentially this is in the title. I have a value that could be null. If it is, I just want to exit with a message. If it's not null, then there's a whole slew of work I need to do with this value.
I've found similar, but not quite this exact situation. And it's the subtle difference that's driving me nuts. Here is my code in java:
if (value == null) {
print("error!");
return;
}
print(value);
doFunStuff(value);
etc(value);
All those methods using value require it to be non-null.
But I'm having a difficult time figuring this out in kotlin. With everything I try, the compiler still insists that value is still nullable and refuses to use it in the functions.
What is the kotlin way of doing this very common code flow?
If your methods truly have non-null parameters, the Kotlin compiler should be smart enough to do a smart cast to Object from Object?.
fun yourMethod(value: Object?) {
if (value == null) {
print("error!")
return
}
print(value) // Smart cast happens here
doFunStuff(value)
etc(value)
}
fun print(value: Object) {
// Implementation
}
fun doFunStuff(value: Object) {
// Implementation
}
fun etc(value: Object) {
// Implementation
}
But you can also force the conversion by using the !! operator (though in this case the compiler will tell you it's not necessary):
fun yourMethod(value: Object?) {
if (value == null) {
print("error!")
return
}
val nonNullValue = value!!
print(nonNullValue)
doFunStuff(nonNullValue)
etc(nonNullValue)
}
fun print(value: Object) {
// Implementation
}
fun doFunStuff(value: Object) {
// Implementation
}
fun etc(value: Object) {
// Implementation
}
If your value is a local variable or a function parameter, you won't have this problem, because the compiler will smart-cast it to not-null.
So, I'm assuming value in this case is a member property.
Option 1 is to copy it to a local variable to use in the function:
val value = value
if (value == null) {
print("error!")
return
}
print(value)
doFunStuff(value)
etc(value)
Option 2 is to use the let or also scope functions to do the same thing, but this might not be a good option here because so much code would become nested. This is more useful when you're only calling one or two functions with the object, in which case, you wouldn't even have to name it (just call it it).
value.let { value ->
if (value == null) {
print("error!")
return
}
print(value)
doFunStuff(value)
etc(value)
}
If your entire function works with this one property, you can avoid the nesting problem like this, if you don't mind it returning something besides Unit:
fun foo() = value.also { value ->
if (value == null) {
print("error!")
return
}
print(value)
doFunStuff(value)
etc(value)
}
Option 3 is to assert non-null every time you use it, but this is very ugly. This is only safe if you know the property is only ever accessed from the same thread this function is ever called on.
if (value == null) {
print("error!")
return
}
print(value!!)
doFunStuff(value!!)
etc(value!!)
Expanding on #Mehul's answer, this would only run the code in the let if the value was not null. If null, you could run the outside process and return from it.
value?.let { nonNullValue ->
print(nonNullValue);
doFunStuff(nonNullValue);
etc(nonNullValue);
}?: run { print("error!") ; return }
That said, since you are no longer needing the return to abort the function if null, you could simply do this and further clean it up replacing the lambda.
value?.let {
print(it);
doFunStuff(it);
etc(it);
}?: print("error!")
Well, have you already tried something like this and this is not what you expect?
value?.let { nonNullValue ->
print(nonNullValue);
doFunStuff(nonNullValue);
etc(nonNullValue);
}
basically the code inside let block will run only if the value isn't null.

Test object member for null before executing IF block

I have the following code:
class Countries {
var list: MutableList<String>? = null
}
val countries = Countries()
if (countries.list!!.isNotEmpty()) {
}
At runtime this will raise an exception because list is null. I can do this instead:
if ((countries.list != null) && countries.list!!.isNotEmpty()) {
}
If I had a boolean member called areInitialized that was nullable, I could create a infix function like this:
infix fun Any?.ifTrue(block: () -> Unit) {
if ((this != null) && this == true) block()
}
and then use it like this:
countries.areInitialized ifTrue {
}
But I can't seem to create something similar for a mutable list.
But I hate having to repeat this test for null on an member field in other parts of code. Is there a simpler way in Kotlin to do this?
I would try to stick to the standard as often as you can. So in your example I wouldn't have introduced that ifTrue-function, but rather used takeIf or takeUnless in combination with the safe operator ?. instead, e.g.:
countries?.takeIf { it.areInitialized == true }
?.also {
/* do something with countries */
}
Or if you must return a value, exchange also with let (or see the other scope functions).
The same then also works for the list within countries:
countries?.takeUnless { it.list.isNullOrEmpty() }
?.also {
/* do something with countries */
it.list!!.forEach(::println)
}

brief function code for null check in kotlin

I have a test function and return Int.
fun test ():Int {
colors?.let { colorsArrayList ->
color1 = colorsArrayList.getOrNull(0)?.let {
return if (HexColorValidator().validate(it)) {
Color.parseColor(it)
} else {
Color.parseColor("#8DE7C1")
}
} ?: kotlin.run {
return Color.parseColor("#8DE7C1")
}
} ?: run {
return Color.parseColor("#8DE7C1")
}
return Color.parseColor("#8DE7C1")
}
}
can I write a brief then now?
return Color.parseColor("#8DE7C1")
this very repeated. can brief this line code?
Whenever I see code with a lot of conditional logic, I try to remember that I can "push" nulls rightward. Instead of handling if/else every time you need to test for null, imagine that you just take what you want (happy path) and pass the nulls on. Eventually, at the end, you'll end up with either the answer you want or null, and can return the value you want.
For example (mostly untested):
fun test() =
colors
?.getOrNull(0)
?.let { if(HexColorValidator().validate(it)) Color.parseColor(it) else null }
?: Color.parseColor("#8DE7C1")
Another way to make this easier to read is to extend String (what I'm presuming you have in colors) to hide the call to HexColorValidator:
fun String.parseColor(): Int? =
if (HexColorValidator().validate(this)) Color.parseColor(this)
else null
And then your test() function gets a bit simpler:
fun test(): Int =
colors
?.getOrNull(0)
?.parseColor()
?: Color.parseColor("#8DE7C1")

Using condition to select the sorting property in Kotlin

I am using sortedBy() to perform sorting on the collection of objects.
Since the order may change depending on the user choice, I've ended up with the following code
val sortedList = if (sortingOrder == WordSortingOrder.BY_ALPHA) {
list.sortedBy { it.word.value }
} else {
list.sortedBy { it.createdAt }
}
Then I perform further actions on the sorted collection.
I realize that sortedBy() method expects a property to be returned.
I wonder if there is a way to embed the sorting condition in one chain of collection methods.
If your properties are of different types you won't be able to select one of them based on some condition as a result for sortedBy, as their common supertype would be inferred as Any and it is not a subtype of Comparable<R> as sortedBy expects.
Instead you can utilize sortedWith method, which takes a Comparator, and provide a comparator depending on the condition:
list.sortedWith(
if (sortingOrder == WordSortingOrder.BY_ALPHA)
compareBy { it.word.value }
else
compareBy { it.createdAt }
)
Comparators for different properties are created here with the kotlin.comparisons.compareBy function.
You can then extract the logic which selects comparator based on sorting order to a function:
list.sortedWith(comparatorFor(sortingOrder))
fun comparatorFor(sortingOrder: WordSortingOrder): Comparator<MyType> = ...
The sortedBy expects any function of type (T) -> R as its parameter. A property is a corner case of that.
Which means you can do this:
val sortedList = list
.sortedBy { if (sortingOrder == WordSortingOrder.BY_ALPHA) it.word.value else it.createdAt}
Or, if you need something more OOP-ish:
enum class WordSortingOrder(val transform: (MyObject) -> Int) {
BY_ALPHA({it.word.value}),
BY_ALPHA_REVERSED({-1 * it.word.value}),
DEFAULT({it.createdAt})
}
val sortedList = list.sortedBy { sortingOrder.transform(it)}
You can do something like:
list.sortedBy { item ->
when(sortingOrder) {
WordSortingOrder.BY_ALPHA -> item.word.value
else -> item.createdAt
}
}
You can make the lambda argument passed to sortedBy conditional:
list.sortedBy(if (sortingOrder == WordSortingOrder.BY_ALPHA) {
{ it: MyType -> it.word.value }
} else {
{ it: MyType -> it.createdAt }
})
You may find using when instead of if more readable in this scenario:
list.sortedBy(when (sortingOrder) {
WordSortingOrder.BY_ALPHA -> { it: MyType -> it.word.value }
else -> { it: MyType -> it.createdAt }
})
If your selectors have different return types then you can simply wrap your existing code within list.let { list -> ... } or use run:
list.run {
if (sortingOrder == WordSortingOrder.BY_ALPHA) {
sortedBy { it.word.value }
} else {
sortedBy { it.createdAt }
}
}
You can then continue chainging calls after the let/run.