Need some help with this one. I have a few objects...
# getting-started
j
Need some help with this one. I have a few objects which implement a generic interface and I have a list of those objects and I"m trying to work with a function. I can unsafe cast to get around this, but is there a method to achieving the same thing without this? Here is a simplified example:
Copy code
interface TestT: Number {
    val clazz: KClassT // Keep reference to the class so we can find the right one later
    fun foo(item: T)
}

// Int object:
object A : TestInt {
    override val clazz = Int::class
    override fun foo(item: Int) {
        // do something
    }
}

// Double object
object B : TestDouble {
    override val clazz = Double::class

    override fun foo(item: Double) {
        // do something
    }
}

fun test() {
    // Working with a list of these objects
    val objs: List<Testout Number> = listOf(A, B)
    
    val myInt = 1
    
    // I'm certain find returns A, but due to forced out projection I get an error.
    val properObj = objs.find {
        it.clazz == myInt::class
    }

    properObj?.foo(myInt) // Receiver type 'Testout Number' contains out projection which prohibits the use of 'fun foo(item: T): Unit'.
}
c
Here's a working example of what you wanted to do: https://pl.kotl.in/dIaO7dU1S This is a very complex topic, but hopefully this working version helps you understand it just a little bit better.