mhadidg
mhadidg

Reputation: 1834

Kotlin function that returns 0 for negative values and the same value for positive ones

I'm a bit annoyed with the line of code below. I'm wondering if there are any build-in function in the Kotlin SDK that could do the same in a more elegant way.

val result = if (value > 0) value else 0

Upvotes: 10

Views: 2677

Answers (1)

IR42
IR42

Reputation: 9682

val result = value.coerceAtLeast(0)

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.ranges/coerce-at-least.html

also you can use

val result = max(0, value)

Upvotes: 19

Related Questions