Kotlin isInfinite()

Kotlin isInfinite()

In Kotlin, the isInfinite() function is used to check if a floating-point number represents positive or negative infinity.

This function is useful for handling special cases in mathematical calculations where a result may be infinite.

In this tutorial, we’ll explore the syntax of the isInfinite() function and provide examples of its usage in Kotlin.

Syntax

The syntax of the isInfinite() function is:

fun Double.isInfinite(): Boolean
fun Float.isInfinite(): Boolean

The function returns true if the number is positive or negative infinity, and false otherwise.

Examples for isInfinite() function

1. Using isInfinite() to Check for Infinity

In this example, we’ll use isInfinite() to check if a result from a mathematical operation is infinite.

Kotlin Program

fun main() {
    val result1 = 10.0 / 5          //2
    val result2 = 10.0 / 0          //Infinity

    println("result1 : $result1")
    println("result2 : $result2")

    println("Is result1 Infinite? ${result1.isInfinite()}")
    println("Is result2 Infinite? ${result2.isInfinite()}")
}

Output

result1 : 2.0
result2 : Infinity
Is result1 Infinite? false
Is result2 Infinite? true

In this example, we perform two mathematical operations that result in a definite number, and Infinity respectively. The isInfinite() function is used to check if the results are infinite, and the outcome is printed.

Summary

In this tutorial, we’ve covered the isInfinite() function in Kotlin, its syntax, and how to use it for checking if a double-precision floating-point number is positive or negative infinity.