What is the reason behind Smart Cast being impossible to perform when referenced class is in another module?

“trust” other modules to do what? That each and every ‘val’ property returns always the same object?

Basically it would mean that those modules are always built together. If there is a change in one module, the other module is always built.

1 Like

If you expect code to be all compiled at the same time you shouldn’t use modules in the first place.

If you read the documentation for modules
https://kotlinlang.org/spec/packages-and-imports.html#modules
it says:

Kotlin module is a set of Kotlin files which are considered to be interdependent and must be handled together during compilation.

1 Like
val foo: String = j.foo

to

j.foo?.let{val fool:String = it}

I do agree with this statement of @yole

Although quite late here to add to this conversation

A smart cast is only valid when multiple accesses of the same property are guaranteed to return the same value. If the property being accessed is defined in a different module from the access location, the module containing the property can be recompiled separately from the module where it’s accessed, breaking the key requirement of the smart cast

I think if someone still want to enforce the smart casting to some degree accross modules, they can use kotlin contracts
For example, I wanted smart casting for non-nullability. For this I simply wrote contract for a function like this

fun <T>enforceNonNullSmartCast(data: T?): T? {
    contract {
        returnsNotNull() implies (data != null)
    }
    return data
}

At call site

        val safeData = enforceNonNullSmartCast(data)
        if(safeData == null) return
        // use smart cast non-null data now

Is this any different than val safeData = data?

2 Likes

Actually no, right after posting this message, it realized I can simply use val safeData = data for non-nullability smart case

1 Like