Infer property type if not null

Viewed 59

I have a function like the following:

fun getCommonItemsFrom(element: Element): List<ElementItem>? =
    if (element.parent is CommonElementWrapper) element.items
    else null

So let's assume that Element has a property called parent, which is of type ElementWrapper? (an interface). And this property may or may not be a concrete instance of CommonElementWrapper.

This function returns the items (that is non-nullable List<ElementItem>) of an Element, as long as the parent property is an instance of CommonElementWrapper, otherwise null will be returned.

So I can use it like this:

if (getCommonItemsFrom(element) == null) {
    return
}

// At this point I can infer that `element.parent` is a `CommonElementWrapper`.
// Since the above condition was not `null`.

if (element.parent.isSomeCommonElementWrapperThing()) {
    // Error: I can't use it this way without first re-checking the parent type.
    // ...
}

But currently I need to double check:

if (element.parent is CommonElementWrapper &&
    element.parent.isSomeCommonElementWrapperThing()) { 
    // ...
}

I was wondering if Kotlin has some way of after a certain function is executed it allows to infer some things from there. Something like:

@InferIfReturnIsNotNull (element.parent is CommonElementWrapper)
fun getCommonItemsFrom(element: Element): List<ElementItem>? = ...
0 Answers
Related