How do I check if a variable declared by Delegates.notNull<Type>() was Initialized in Kotlin?

Viewed 141

I want to programmatically check if a variable I declared using the by Delegates.notNull() has been declared in my code.

val max = arr.maxOrNull()
    var num by Delegates.notNull<Int>()
    if (max != null) {
        if(max >= 0){
            for(i in 1..max){
                if (!arr.contains(i)){
                    num = i
                    break
                }
            }
            if(!(this::num.isInitialized)) num = max + 1 //TODO: How do I check if num variable has been initialized
        }
    }
    return num

I have tried to use the class::num.isInitialized method, but the method I am creating is not in a class; it's just a solution to an algorithm. I also tried creating a class for the solution and making the num variable a field variable; so that I can access it in the class, and this context can work. But it seems the class::num.isInitialized is only used for lateinit variables, and I can't use lateinit var num: Int because you can't use lateinit for primitive datatypes.

1 Answers
import kotlin.properties.Delegates

object Test {

  private var num by Delegates.notNull<Int>()

  fun test(arr: Array<Int>): Int {
    val min = 1
    val max = arr.maxOrNull() ?: min
    for (i in min..max) {
      if (i !in arr) {
        num = i
        break
      } else if (i == max) {
        num = max + 1
      }
    }
    return num
  }

}

private val arr1 = arrayOf<Int>()
private val arr2 = arrayOf(5, 44, 3, 975, 1, 123, 2, 4)
private val arr3 = arrayOf(1, 4, 3, 2)

println(Test.test(arr1))   // Prints 1
println(Test.test(arr2))   // Prints 6
println(Test.test(arr3))   // Prints 5
Related