Type inference failed, but IntelliJ displays no errors

This is a very simplified version of the problematic function:

fun CoroutineScope.testAsync(any: Any): Deferred<String> = async {
    if (any is String) return@async any

The compilation error:

Type inference failed. Expected type mismatch: inferred type is Deferred<Any> but Deferred<String> was expected

If I explicitly specify the type in async (async<String>), or if I cast any (any as String) it compiles fine. However, in both cases IntelliJ issues a warning that this is unneeded and offers to remove it, leading to a compilation error.

Am I doing something wrong?

I’ve found a simpler way to reproduce this that doesn’t involve coroutines:

fun test(any: Any): Sequence<String> = sequence {
    if (any is String) yield(any)

IntelliJ indicates that any is smart cast to String, but this doesn’t seem to happen.

Interestingly, if I remove the explicit return type it works fine.

I guess you are using kotlin 1.3.4. They enabled a new type inference in intellij but it’s not yet used for building. I think they choose to do this in order to find the few inconsistencies that still exist without breaking automated builds.
You should create an issue for it here: http://kotl.in/issue

1 Like

Thank you, somehow I completely missed the fact that the new type inference algorithm is only used in the IDE. It looks like most issues related to related to the new algorithm are the exact same so I will leave it alone for now.

Yeah I don’t think they communicated this very well. It’s quite an unusual situation so it should have been made more obvious. But then, maybe they hoped this will only affect some wired corner cases.

That said there are ways to enable the new type inference for the build as well. There should be an option in intellij and if you use grade there is some compiler argument you can use. I can’t remember what it was exactly though.

The compiler argument is -XXLanguage:+NewInference, see https://youtrack.jetbrains.com/issue/KT-31507.

And yes, please report such bugs to the issue tracker. Thanks to the recent feedback we’ve already fixed a lot of new inference regressions.

1 Like

IntelliJ indicates that any is smart cast to String , but this doesn’t seem to happen

This particular case is an example of new inference inferring types better than old inference. And since the project is compiled with old inference, you get the error only on compilation.