Sorry, very nitty-gritty Kotlin contracts question...
# announcements
d
Sorry, very nitty-gritty Kotlin contracts question - thought it best to ask on SO https://stackoverflow.com/q/59245615/97777
s
I had the same question a few weeks back. At least for reified type parameters this should be achievable but currently isn’t. Here is my playground code to test for it, as you can see currently the compiler says ‘no’: <https://pl.kotl.in/zeTyPpnkc> And as long as you only use the contract to smart-cast the argument non-reified versions should be achievable as well (given that smart-cast is a pure compile-time feature (am I wrong??)) Anyway, the Kotlin devs didn’t come around to doing it (hmm, or is that part of the new TypeInference, that we can opt into?!?) <https://blog.jetbrains.com/kotlin/2019/06/kotlin-1-3-40-released/#new-type-inference>
d
We seem to agree - I wonder if this is a feature we can expect as contracts mature.
s
I checked the new inference, it still doesn’t work.
Copy code
fun <T:Any> haveSameClass(first: T, other: Any?): Boolean {
    contract {
        returns(true) implies (other is T)
    }
    if (first === other) return true
    return other!=null && first.javaClass == other.javaClass
}
will fail with on
is T
with: can not check for instance of erased type, while the inline-version
Copy code
inline fun <reified T:Any> haveSameClass(first: T, other: Any?): Boolean {
    contract {
        returns(true) implies (other is T)
    }
    if (first === other) return true
    return other!=null && first.javaClass == other.javaClass
}
still fails on
is T
but with references to type parameters are forbidden in contracts
👍 2
s
Thank you for reporting. It is a known limitation: https://youtrack.jetbrains.com/issue/KT-28298
d
Splendid, thanks for clarifying
s
Feel free to vote for it 😊
👍 3