Jim
Jim

Reputation: 4415

Minimum of 2 nullable numbers

I have the following code:

val num1: Int? = someObject.number
val num2: Int? = anotherObject?.anotherNumber
val numToFallBack = 2

val result: Int
if(number1 != null && number2 != null) {
   result = minOf(number1, number2)
}
else {
   result = number1?:number2?:numToFallBack
}

Basically I would like to end up with a number that is either the smaller of num1 and num2 taking into account that either or both could be null. In the case that both are null use a default value.
This code snippet above I think is too java verbose. How could I code this in a more Kotlin way?

Upvotes: 2

Views: 1831

Answers (3)

Brian D'Astous
Brian D'Astous

Reputation: 1358

I defined this utility function for myself. Unlike using listOfNotNull with minOrNull, it avoids allocating memory on the heap:

fun <T : Comparable<T>> minOfNullable(a: T?, b: T?): T? {
    return when {
        a == null -> b
        b == null -> a
        else -> minOf(a, b)
    }
}

Upvotes: 1

Mario Lenci
Mario Lenci

Reputation: 10542

You can use the collections operators to get the min value of a group of nullable numbers

listOfNotNull(num1, num2).minOrNull() ?: numToFallBack

if you only want to take non-zero numbers as requested in this comment, you can do this:

listOfNotNull(num1, num2).filter { it != 0 }.minOrNull() ?: numToFallBack

Upvotes: 4

Francesc
Francesc

Reputation: 29260

You can use a when statement,

val result = when {
    number1 != null && number2 != null -> min(number1, number2)
    number1 != null -> number1
    number2 != null -> number2
    else -> numToFallBack
}

Edit: if we want to choose the non-zero number, we can do this

val result = when {
    number1 != null && number2 != null -> when {
        number1 == 0 -> number2
        number2 == 0 -> number1
        else -> min(number1, number2)
    }
    number1 != null -> number1
    number2 != null -> number2
    else -> numToFallBack
}

Edit 2: if we do not want zero at all

Option 1

number1 = if (number1 == 0) null else number1
number2 = if (number2 == 0) null else number2

val result = when {
    number1 != null && number2 != null -> min(number1, number2)
    number1 != null -> number1
    number2 != null -> number2
    else -> numToFallBack
}

Option 2:

val result = when {
    number1 != null && number2 != null -> when {
        number1 == 0 && number2 != 0 -> number2
        number2 == 0 && number1 != 0 -> number1
        number1 == 0 && number2 == 0 -> numToFallBAck
        else -> min(number1, number2)
    }
    number1 != null && number1 != 0 -> number1
    number2 != null && number2 != 0 -> number2
    else -> numToFallBack
}

Upvotes: 1

Related Questions