The following code should be self explaining. I’ve got a list of Test objects, the function test get’s a downcasted test object supplied. Since list can only have test objects, the object must be a Test. But kotlin doesn’t recognize this.
val list = mutableListOf<Test>(Test())
fun main() = test(list[0])
fun test(obj: Any) {
if (obj in list) { // No auto casting :c
obj.print() // Fails
(obj as Test).print() // Workaround
}
}
class Test {
fun print() = println("Hello World!")
}
The Kotlin compiler simply doesn’t know that List<T>.contains(x) == true implies that x is T. I’m sure that could be somehow added with contracts, but currently, the compiler only recognises simple conditions and casts like is, as? and so on.
The reason why contains does not yet use contracts is that it’s a member function of List and contracts only work for top level functions right now. I guess this will be added once contracts are expanded to work with member functions.