Custom smart casts?

I think I saw this in Typescript, not in Kotlin, but I want to double check.

When using XML nodes, a boolean check and a cast often go together. Is there a way to make the check lead to a smart cast? In this case from Node to Element.

for (child in documentElement.childNodes.toList()) {
    if (child.isElement) {
        // Here, could smart cast `child` from Node to Element
    }
}
...
val Node.isElement: Boolean
    get() = nodeType == Node.ELEMENT_NODE

There is an experimental feature in Kotlin called contracts which can do that. See KEEP/kotlin-contracts.md at master · Kotlin/KEEP · GitHub

2 Likes

Cool, it works.

It looks like it doesn’t work for getters, so I needed to change isElement to isElement()

1 Like

Contracts are still experimental. So getters will probably work in the future. But there is no good design for it yet. Same for members. Right now only top level functions are supported.

1 Like