https://kotlinlang.org logo
#compiler
Title
# compiler
o

Olaf Gottschalk

02/14/2023, 4:44 PM
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

Ayfri

02/14/2023, 4:46 PM
I think you have to use
Blah<*>
instead of
Blah<Any?>
o

Olaf Gottschalk

02/14/2023, 4:48 PM
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...
4 Views