2

I would like to tell the compiler that if a function returns, one of its parameters is of a given type.

Contracts seems to give me that power, but does not work when I want to signal an otherwise erased type.

@ExperimentalContracts
fun <T> List<T>.isListOfInt(): Boolean {
    contract {
        returns(true) implies (this@isListOfInt is List<Int>)
    }
    return TODO("some way that I know")
}

This fails because this@isListOfInt is List<Int> does not compile - Cannot check for instance of erased type: List<Int>.

I understand that the current contracts specification is a Kotlin DSL, and so subject to this restriction, but at the same time being able to imply an otherwise erased type would be tremendously powerful.

Is there any way to achieve this effect now, or is it likely to be possible in future contracts implementations?

2 Answers 2

1

I wrote a feature-request for the case with reified type parameters. E.g.

@ExperimentalContracts
// would be pretty useful for custom equals-methods.
inline fun <reified T:Any> T.hasSameClassAs(other: Any?): Boolean {
    contract {
        returns(true) implies (other is T)
    }
    if (this === other) return true 
    return other!=null && other is T
}

That should be possible, shouldn't it? https://youtrack.jetbrains.com/issue/KT-35366?project=kt

Turns out it's a duplicate for another request that's already one year old: https://youtrack.jetbrains.com/issue/KT-28298 (which can be voted up ;) )

0

There is basically no way to prove that List<Any> is List<Int> because List<Any> can also be MutableList<Any>. So someone can add not Int item to it after your check.

I suggest you declaring ifIntList function which will work like ?.let, but instead of calling passed block when the receiver isn't null ifIntList will call it when receiver list contains only Int elements:

fun List<*>.copyIfIntList(): List<Int>? =
    if (all { it is Int }) map { it as Int }
    else null

inline fun <R> List<*>.ifIntList(block: (List<Int>) -> R): R? =
    copyIfIntList()?.let(block)

Use case:

val unknownList: List<*> = listOf(1, 2, 3)
unknownList.ifIntList { intList ->
    println(intList.sum()) 
}

Contracts which imply on generic type parameters still can be pretty useful for immutable classes. So if you need such contracts, you can suggest adding them on youtrack.jetbrains.com/issues/KT.

1
  • This is a good suggestion. Unfortunately I specifically wanted to be able to interact with flow-typing, hence my wish for contract support Commented Dec 10, 2019 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.