NotNull operation on <R: Any?>? is ambiguous


#1

I can instead use Optional. but is not a solution for this.

inline fun <R : Any?> Test<R>.test(block: (R) -> Unit) {
    // for some resaon, x: R? is always R here. need (x!!)
    //
    // this is what I need. but ugly code.
    block(x as R) // x is type of R, R is nullable, need doing with x even it is null.


    // x!! not work, because R may null
    // x?.foobar() not work, because R may null
    // 
    x?.run(block) ?: println("** block not called")
}

class Test<R : Any?>(val x: R?)

fun main(args: Array<String>) {
    val s: Test<String?> = Test(null)
    s.test {
        println(it?.hashCode())
    }
}

print:

null
** block not called


#3

I think what you want is for R to be limited to Any (not Any?), then place the question mark on the value’s type… This does what I think you’re trying to do:

inline fun <R : Any> Test<R>.test(block: (R) -> Unit) {
    if (x != null) {
        block(x)
    } else {
        println("Block not called")
    }
}

class Test<R : Any>(val x: R?)

fun main(args: Array<String>) {
    val s: Test<String> = Test(null)
    val p: Test<String> = Test("abc")

    s.test { println(it.hashCode()) }
    p.test { println(it.hashCode()) }
}

#4

Yes, Optional<R> where R: Any is more readable than R where R: Any? , but for some resaon, R? where R: Any? will happen some time.