why does `foo::class` return `KClass<out String...
# announcements
n
why does
foo::class
return
KClass<out String>
instead of
KClass<String>
, and...what are my options if I actually want the latter?
I guess I can just cast it for now 🤷‍♂️
d
Because you are getting the actual runtime type of
foo
. It might be a subtype of the static type (
val foo: A = B()
where
class B : A()
) - In case of
String
that is not possible, but the compiler cannot rely on that (someone might make it
open
at some point and then you have a problem with separate compilation). If you want
KClass<String>
use
String::class
or something like this.
💯 2
n
thanks @diesieben07. yeah I think that makes sense -- even though I'm using a generic type parameter, you still don't know (in code, at least) exactly what type it is
I guess what I'd need to really solve this is for this line:
Copy code
fun <T : Component> addComponent(c: T) {
I need some way to guarantee that
c
is exactly a type T, and not simply a subclass of T. but I don't think there's a way to do that.
d
No there isn't, and that violates a core principle of OOP.
If
A
extends
B
then it must be okay to pass a
A
everywhere that expects a
B
, otherwise
A
should not extend
B
.
n
liskov substitution principle right?
👌 1
the class
addComponent
calls uses
T
in both in and out positions though, so...
d
I think you need to show more code...
n
can do, in a few hours