I am not really sure if this channel is correct fo...
# compiler
o
I am not really sure if this channel is correct for my question... I am having big difficulties understand an inferred type in a sealed class (abstract also does not work) hierarchy with a generic type in the base type... If I am not in the right channel, please excuse me asking here... 😉
Copy code
sealed class Blah<T> {
    abstract fun doSomething(): T
    abstract fun doAnotherThing(a: T)
}

object A : Blah<Int>() {
    override fun doSomething(): Int = 42
    override fun doAnotherThing(a: Int) {}
}

object B : Blah<String>() {
    override fun doSomething(): String = "42"
    override fun doAnotherThing(a: String) {}
}

// inferred type is Blah<out Any>
fun gimmeBlah() = if (Random.nextBoolean()) A else B
// error is Type mismatch. Required: Blah<Any?> Found: A
fun doesNotCompile(): Blah<Any?> = if (Random.nextBoolean()) A else B
I do NOT understand, why the inferred type introduces the "out" variance.... it does not make sense to me (and does not work in my context....)
a
I think you have to use
Blah<*>
instead of
Blah<Any?>
o
Wow. Thanks. You got this even before I was finished typing. Of course. This is always confusing when * means something other than Any.....
But it makes sense...