Exerosis
12/18/2021, 9:55 PMDominaezzz
12/18/2021, 10:42 PMExerosis
12/19/2021, 2:32 AMval array = arrayOf("first", "second", "third");
fun String.example() { println(this) }
fun foo(bar: String?) {
if (bar in array)
bar.example()
}
In this example because bar is in the array... we know that bar is not null since the array is of nonnullable strings.ephemient
12/19/2021, 4:27 AMval array = arrayOfNulls<String>(3) as Array<String>
val bar: String? = null
check(bar in array)
will succeed at runtimeJordan Stewart
12/19/2021, 9:09 AMarrayOfNulls<String>(3) as Array<String>
might confound lots of other things that people would generally expect to work too 😂Jordan Stewart
12/19/2021, 9:21 AMcontains
is
public operator fun <@kotlin.internal.OnlyInputTypes T> Array<out T>.contains(element: T): Boolean {
return indexOf(element) >= 0
}
Giving it a quick go, it seems possible to define a function that does allow a smart cast:
fun <T : Any> Array<T>.smartContains(element: T?): Boolean {
contract {
returns(true) implies (element != null)
}
return indexOf(element) >= 0
}
val array = arrayOf("first", "second", "third");
fun String.example() { println(this) }
fun foo(bar: String?) {
if (array.smartContains(bar))
bar.example()
}
That said, Kotlin doesn't appear to support contracts inside operator functions at the moment, so this function couldn't be included alongside the original one anyway. And I have no idea if there would be other consequences of including it, e.g. overload ambiguity (possibly not because of the nullability differences, but 🤷)Exerosis
12/19/2021, 11:15 PM