Type inference problem with classes with base class and interface

I’ve recently encountered the following type inference issue using Kotlin 1.2.71 - I just wanted to double check my analysis of the problem.

A simplified version of the problem code is shown below:

abstract class Base

interface MyInterface

class TypeA: Base(), MyInterface

class TypeB: Base(), MyInterface

fun useBase(thing: Base) {}

fun createAndUse(useA: Boolean) {
    val thing = if (useA) {
    } else {

The error occurs when trying to use thing, and the message is “Type mismatch: inferred type is Any but Base was expected”.

I think this is happening because the type that is chosen is the ancestor of TypeA, TypeB, Base and MyInterface, and the only choice that satisfies all of these is Any. Kotlin cannot in this case choose something like Base & MyInterface, as there is no concept of this type.

The fix (remaining on 1.2.71) is to specify explicitly that thing is of type Base. Would future versions of Kotlin address this?

Works as you expect in 1.3.41.

1 Like