Different behavior when passing object to function or constructor


#1

I am using lots of anonymous object that implement 1 interface, but when I pass these to a constructor of a generic class, the compiler complains: Error:(33, 9) Kotlin: ‘public’ property exposes its ‘local’ type argument .

I have to explicitly add a type argument to the constructor to make the error go away. But I don’t like the duplication of the interface name.

When I pass the same anonymous object to a generic function, the compiler accepts it and and uses the implemented interface as the type.

Here is an example:

fun <T> doSomething(argument : T) = argument

class HoldSomething<T>(toHold: T)

class Test {
    // Inferred type: Runnable
    val initByMethod = doSomething(object: Runnable {
        override fun run() { }
    })

    // Expected inferred type: HoldSomething<Runnable>
    // Actual: 'public' property exposes its 'local' type argument <no name provided>
    val initByClass = HoldSomething(object: Runnable {
        override fun run() { }
    })

    // Type: HoldSomething<Runnable>
    val initByClass2 = HoldSomething<Runnable>(object: Runnable {
        override fun run() { }
    })
}

Is this by design or is this a bug?