How to make NaN or POSITIVE_INFINITY compilation time constant in Kotlin?

I tried:

import kotlin.Double.Companion.POSITIVE_INFINITY
import kotlin.Double.Companion.NaN

const val inf = POSITIVE_INFINITY
const val nan = NaN

But I get:

The initializer 'Const' val 'must be a constant value


EDIT:

The reason I need to do this is because Junit5 parameterized tests :

 @ParameterizedTest
 @ValueSource(doubles = doubleArrayOf(nan, inf, -2* epsilon,  1.5, -0.5, 1.0 + 2* epsilon))
 fun ensureNotAProbability(number: Double)
 {
     ...
 }  

Due to some limitations of Java annotations (described in this SO answer ), things passed to annotation can only be compile-time constants. So I need NaN compilation time, positive and negative infinity.

+4
source share
2 answers

As a workaround, you can use the fact that the IEEE 754 standard guarantees that it 0.0 / 0.0will be NaN and 1.0 / 0.0equal to + ∞:

@Suppress("DIVISION_BY_ZERO")
const val NAN: Double = 0.0 / 0.0

@Suppress("DIVISION_BY_ZERO")
const val INFINITY: Double = 1.0 / 0.0

fun main(args: Array<String>) {
    println(NAN) // NaN
    println(INFINITY) // Infinity
} 
+5

-. :

import kotlin.Double.Companion.POSITIVE_INFINITY as inf
import kotlin.Double.Companion.NaN as nan
+2

Source: https://habr.com/ru/post/1686881/


All Articles