I want a function to take a `KClass` that extends ...
# announcements
t
I want a function to take a
KClass
that extends a sealed class. Is there anyway to specify this at compile-time, or is this a run-time check?
In java I think there is something like
T extends MySealedBaseType
or some such.
s
The
sealed
keyword is not part of the type of the class. If you do
fun <T: SomeClass> myFunction(param: T)
, the compiler can’t guarantee that
SomeClass
is a sealed class. So, yes, you’d need run-time reflection (on the
param
in the example I gave)
t
so that's true even w/o the sealed? I can't specify that it has to come for a type that extends/implements another "base" type?
s
If your
SomeClass
is a
sealed class SomeClass
, then your
myFunction
is fine. But if you would remove the ‘sealed’ part (
class SomeClass
), your definition of
myFunction
would still compile fine.
t
right. but in your example "T" would still be anything. not something that's derived from
MyBaseType
s
The
<T : SomeClass>
part ensures that
T
is either a
SomeClass
or a sub-class of
SomeClass
.
t
ahh, I see. ok thanks!
j
at compile time only, right? isn’t this a situation where type erasure comes into play? 🤔
s
Yes and no:
T
in the JVM (and Kotlin) is erased as a plain
SomeClass
during runtime. I think that Jonross’ question was more about if the compiler could check if a type-parameter is a sealed class or not when provided to a function or a class-instantiation.
(PS: During runtime, use the
KClass#isSealed
property, if you need to check this)
1
n
I don't think it's so much about type erasure in this particular case
It's more about limitations in how you can constrain generics
There just isn't any other way that I know of to constrain a generic, other than specifying a class, and covariance
You can't constrain a generic on characteristics of a class