The absolute value of a number is its non-negative value irrespective of its sign. In Kotlin, you can simply find the absolute value using the abs function. Kotlin provides this functionality for various number types, including Int, Double, Float, and Long.
Using the abs() Function
The abs() function is part of the Kotlin Standard Library. Depending on the type of number (such as Int, Double, etc.), Kotlin automatically chooses the correct abs() implementation to ensure precision.
Example with Int
import kotlin.math.abs
fun main() {
val number: Int = -10
val absoluteValue = abs(number)
println("Absolute value of -10 is: " + absoluteValue)
}
In this example, abs() takes an Int, and returns the absolute value of -10, which is 10.
Example with Double
import kotlin.math.abs
fun main() {
val number: Double = -3.14
val absoluteValue = abs(number)
println("Absolute value of -3.14 is: " + absoluteValue)
}
This is another example where abs() handles a Double type, returning 3.14 for the input -3.14.
Example in a Function
The abs() function can also be used when defining your own functions:
import kotlin.math.abs
fun getAbsoluteValue(number: Int): Int {
return abs(number)
}
fun main() {
val number: Int = -25
println("Absolute value of -25 is: ${getAbsoluteValue(number)}")
}
This example demonstrates how you can wrap the abs() function within another function, adding more specific functionality or simplifying calls in your code.
Conclusion
Leveraging the abs() function in Kotlin is straightforward. It enhances code readability and ensures that you're obtaining absolute values with precision. Keeping in mind the data type you are working with will help you use abs() more effectively across your applications.