genericskotlinassertjkotlin-reified-type-parameterskotlin-contracts

Kotlin Contracts: assert instance on reified type parameter


I'm trying to write an assert function that checks if a given object is of a type T:

@UseExperimental(ExperimentalContracts::class)
inline fun <reified T> assertIsInstance(value: Any?) {
    contract {
        returns() implies (value is T)
    }

    Assertions.assertThat(value).isInstanceOf(T::class.java)
}

The function uses AssertJ to do the concrete assertion but I'm willing to let the compiler know that after its execution, the value is of type T so that a smartcast is possible. It seems like this does not work because:

Error in contract description: references to type parameters are forbidden in contracts

Is there another way to achieve this behavior? What's the issue here? Will this eventually be possible?

(Using Kotlin v1.3)


Solution

  • At some point there were some (deeply technical) concerns regarding support of such constructions in an IDE, but it's possible that this limitation will be relaxed in the future.