Calling reified inline function with wrong inferred type: no compiler error

221 views Asked by At

Can anyone explain why there's no compiler error when I use an inline function in a function call with the wrong inferred type, yet there's a compiler error when I explicitly mention the type?

interface Foo

class FooBar : Foo

inline fun <reified T: Foo> createFoo() : T {
    return T::class.java.getConstructor().newInstance()
}

fun fooFun(foo: String) {}

fun main() {
    val foo1 = createFoo<FooBar>() // all good 
    val foo2 = createFoo<String>() // compiler error
    val foo3: String = createFoo() // compiler error
    
    fooFun(createFoo()) // all good at compile time, fails at runtime: why? ¯\_(ツ)_/¯
}

I would expect that calling fooFun(createFoo()) should also result in a compiler error.

0

There are 0 answers