5

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:

Const 'val' initializer should be a constant value


EDIT:

The reason I need to do this is because of Junit5's parametrized 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) the things 'passed to an annotation' can only be compile-time constants. Therefore I would need a compile time NaN, positive, and negative infinities.

Martin Drozdik
  • 12,104
  • 17
  • 74
  • 138

2 Answers2

7

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

@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
} 
hotkey
  • 127,445
  • 33
  • 333
  • 310
2

You don't need to redefine anything. Just import with an alias:

import kotlin.Double.Companion.POSITIVE_INFINITY as inf
import kotlin.Double.Companion.NaN as nan
Michael
  • 37,794
  • 9
  • 70
  • 113