Search code examples
kotlintypescastingdoublenan

Float.isNaN 'receiver type mismatch' error in Kotlin


I am new to Kotlin and having an issue with Kotli'ns built-in FLoat.isNaN and Double.isNaN functions. When using the Float.isNaN function to test for NaN equalt of a float arraylist I receive the error:

Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:

  • public inline fun Double.isNaN(): Boolean defined in kotlin public
  • inline fun Float.isNaN(): Boolean defined in kotlin

Pseudocode is listed below, appreciate any help:

var scores = arrayListOf<Float>()
val todaysResult = scores[0]
if(Float.isNaN(todaysResult)) {
    todayResultNumericTextView!!.text = "-"
} else {
    todayResultNumericTextView!!.text = Math.round(todaysResult).toString() + "%"
}

Solution

  • isNaN is an extension function on Float and Double (not a "static" method, unlike in Java!) This means you must invoke it with the value as the receiver.

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

    Instead of

    Float.isNaN(todaysResult)
    

    you want

    todaysResult.isNaN()
    

    This is also indicated by the error message:

    public inline fun Double.isNaN(): Boolean defined in kotlin
    public inline fun Float.isNaN(): Boolean defined in kotlin

    The syntax Float.isNaN() indicates that this function takes a receiver of type Float.


    See also: Extensions (Kotlin reference)