Explore Kotlin contracts for Boolean check functions
Jolanrensen opened this issue · 0 comments
Jolanrensen commented
It's odd that after a
if (myCol.isColumnGroup())
check you still need an explicit cast to ColumnGroup<*>
to be able to call columnsCount()
on myCol
. The check should tell the compiler that it's actually a column group, similar to what an myCol is ColumnGroup<*>
would do.
This is actually possible with Kotlin contracts:
@OptIn(ExperimentalContracts::class)
public fun AnyCol.isColumnGroup(): Boolean {
contract {
returns(true) implies (this@isColumnGroup is ColumnGroup<*>)
}
return kind() == ColumnKind.Group
}
makes
if (myCol.isColumnGroup()) {
myCol.columnsCount() // compile
} else {
myCol.columnsCount() // not compile
}
Unfortunately contracts aren't all-powerful (yet):
@OptIn(ExperimentalContracts::class)
public inline fun <reified T> AnyCol.isType(): Boolean {
contract {
returns(true) implies (this@isType is DataColumn<T>) // !! Cannot check for instance of erased type: DataColumn<T> :(
}
return type() == typeOf<T>()
}